11
votes

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.

3
Look at this question. Maybe it will help: stackoverflow.com/q/1992132/891391 - yatul

3 Answers

21
votes

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.

0
votes

You can consume services which are created/managed by some IOC container (Spring, Guice)

You could create a ContextAware implementation and Pull out the beans as and when needed from Servlet

0
votes

You could use JNDI, the Java Naming and Directory Interface, and @Resource to inject it.