Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use dependency injection in servlet?

How to inject an object to a servlet?

I mean, that I cannot use a constructor DI because servlets are instantiated by a servlets container.
And I also don't see a nice way of implementing setter-based DI for a servlet.

Should I use servlet listener? Are there any best-practices?

P.S. I don't have neither Spring nor Guice nor any other DI framework, I'm interested in manual dependency injection.

like image 880
Roman Avatar asked May 11 '12 09:05

Roman


1 Answers

This is possible under Servlet 3.0. You register a ServletContextListener which programmatically registers Servlet instances with the addServlet(String, Servlet) method of ServletContext just before the app starts. Since you're instantiating the Servlet instances yourself, you can give them proper constructors and inject dependencies.

I created an example a while ago that illustrates the basic technique.

like image 136
Sean Reilly Avatar answered Oct 02 '22 14:10

Sean Reilly