Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Constructor dependency injection with Servlet 3.0?

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?
like image 272
deamon Avatar asked Jan 02 '10 17:01

deamon


2 Answers

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 its custom API to add preconfigured servlet instances.

like image 88
Stefan L Avatar answered Sep 19 '22 06:09

Stefan L


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

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

like image 31
Dhanji R Prasanna Avatar answered Sep 18 '22 06:09

Dhanji R Prasanna