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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10549241/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:30:41  来源:igfitidea点击:

How to use dependency injection in servlet?

javaservletsdependency-injection

提问by Roman

How to inject an object to a servlet?

如何将对象注入 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.

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

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

我应该使用 servlet 侦听器吗?有没有最佳实践?

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

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

回答by Sean Reilly

This is possible under Servlet 3.0. You register a ServletContextListenerwhich 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.

这在 Servlet 3.0 下是可能的。您注册一个ServletContextListener,它会在应用程序启动之前以编程方式使用ServletContextaddServlet(String, Servlet)方法注册 Servlet 实例。由于您自己实例化 Servlet 实例,您可以为它们提供适当的构造函数并注入依赖项。

I created an examplea while ago that illustrates the basic technique.

不久前我创建了一个示例来说明基本技术。

回答by Jigar Joshi

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

您可以使用由某些 IOC 容器(Spring、Guice)创建/管理的服务

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

您可以创建一个 ContextAware 实现并在需要时从 Servlet 中提取 bean

回答by ewernli

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

您可以使用 JNDI(Java 命名和目录接口)并@Resource注入它。