在我的Stripes应用程序中,我定义了以下类:
MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
private SomeService someService;
private AnotherService anotherService;
// remaining implementation omitted
}
此应用程序的服务层使用Spring在XML文件中定义并连接一些服务bean。我想将实现SomeService
和AnotherService
的bean注入MyServletListener
,这可能吗?
答案 0 :(得分:24)
这样的事情应该有效:
public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
@Autowired
private SomeService someService;
@Autowired
private AnotherService anotherService;
public void contextInitialized(ServletContextEvent sce) {
WebApplicationContextUtils
.getRequiredWebApplicationContext(sce.getServletContext())
.getAutowireCapableBeanFactory()
.autowireBean(this);
}
...
}
你的听众应该在ContextLoaderListener
的春天web.xml
之后宣布。
答案 1 :(得分:12)
使用SpringBeanAutowiringSupport
类稍微简单一点
你所要做的就是:
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
所以使用axtavt的例子:
public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
@Autowired
private SomeService someService;
@Autowired
private AnotherService anotherService;
public void contextInitialized(ServletContextEvent sce) {
SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
}
...
}