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.
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.
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