如何在servlet中使用依赖注入?

问题描述:

如何将对象注入servlet?

How to inject an object to a servlet?

我的意思是,我不能使用构造函数DI,因为servlet由servlets容器实例化。
我也没有看到为servlet实现基于setter的DI的好方法。

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.

我应该使用servlet监听器吗?有没有最好的做法?

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

P.S。我既没有Spring也没有Guice,也没有任何其他DI框架,我对手动依赖注入感兴趣。

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

这个可以在Servlet 3.0下使用。您注册了 ServletContextListener ,它以addServlet(String,Servlet)应用程序启动前的一个ServletContext方法。由于您自己实例化Servlet实例,因此可以为它们提供正确的构造函数并注入依赖项。

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.