views:

352

answers:

2

Since Servlet 3.0 it is possible to register Servlet instances programmatically with javax.servlet.ServletContext#addServlet. This class has also a createServlet method which analyses some annotations and performs dependency injection. I wonder if I need this method if I don't need the annotation processing. I'd like to have a servlet with a usual constructor to set required dependencies via dependency injection.

@Inject
public MyServlet(SomeDependency sd) {  // Constructor
  ...
}

Questions:

  • Is it possible to construct a servlet instance "by hand" without createServlet? (new MyServlet())
  • Is it possible to use the dependency injection mechanism of a Java EE server to perform constructor injection? How to do it? Or is a separate DI framework like Guice required?
+2  A: 

The recent Java EE 6 standard now supports dependency injection for servlets, the relevant part is called JSR-299 or CDI. The JSR-299 reference implementation, JBoss weld, can be deployed into servlet containers like Tomcat or Jetty as well if you don't want to use a full Java EE 6 application server like glassfish v3 e.g.

By the way, with an embedded Jetty server you can use it's custom API to add preconfigured servlet instances.

Stefan L
Thanks, JSR-299 is what i'm looking for. The Weld documentation says: "We may obtain an instance of TextTranslator by injecting it into a constructor, method or field of a bean, or a field or method of a Java EE component class such as a servlet." http://docs.jboss.org/weld/reference/1.0.0/en-US/html/intro.html It seems like constructor injection is not possible with servlets.
deamon
A: 

Guice does this out of the box without the need for Java EE servers.

http://code.google.com/p/google-guice/wiki/ServletModule

Dhanji R Prasanna
Guice adds a layer above servlets. That was useful before Java EE 6. Today dependency injection is part of Java EE and I would prefer to use it without an additional framework - if possible.
deamon