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:
createServlet
? (new MyServlet()
)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.
Guice does this out of the box without the need for Java EE servers.
http://code.google.com/p/google-guice/wiki/ServletModule
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With