spring servlet 中的自动装配
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11843690/
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
Autowiring in servlet
提问by Mahmoud Saleh
i want to use spring autowiring in servlet so here's my code:
我想在 servlet 中使用 spring 自动装配,所以这是我的代码:
@Configurable
public class ImageServlet extends HttpServlet {
@Autowired
private SystemPropertyDao systemPropertyDao;
@Override
public void init() throws ServletException {
String imagePath = systemPropertyDao.findByID(StaticParam.CONTENT_FOLDER);
}
while the SystemPropertyDaois annotated with @Repository
而SystemPropertyDao注释为@Repository
and my applicationContext.xml:
和我的applicationContext.xml:
<context:component-scan base-package="com.basepackage" />
<mvc:annotation-driven />
<context:annotation-config />
<context:spring-configured/>
web.xml:
网页.xml:
<servlet>
<servlet-name>imageServlet</servlet-name>
<servlet-class>com.xeno.basepackage.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>imageServlet</servlet-name>
<url-pattern>/myimages/*</url-pattern>
</servlet-mapping>
sometimes the autowiring works and sometimes it doesn't (the reference to the spring bean systemPropertyDao is null), can anyone please tell me if i am missing something?
有时自动装配有效,有时无效(对 spring bean systemPropertyDao 的引用为空),谁能告诉我我是否遗漏了什么?
回答by Mahmoud Saleh
I followed the solution in the following link, and it works fine: Access Spring beans from a servlet in JBoss
我遵循以下链接中的解决方案,它工作正常: Access Spring beans from a servlet in JBoss
public class MyServlet extends HttpServlet {
@Autowired
private MyService myService;
public void init(ServletConfig config) {
super.init(config);
SpringBeanAutowiringSupport.processInjectionBasedOnServletContext(this,
config.getServletContext());
}
}
回答by Stefan
Remove the @Configurableannotation from your servlet and add:
@Configurable从您的 servlet 中删除注释并添加:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext (this);
at the first line of your init() method.
在 init() 方法的第一行。

