在我的 Stripes 应用中,我定义了以下类:
MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {
private SomeService someService;
private AnotherService anotherService;
// remaining implementation omitted
}
这个应用程序的服务层使用 Spring 在 XML 文件中定义和连接一些服务 bean。我想将实现 SomeService
和 AnotherService
的 bean 注入(inject)到 MyServletListener
中,这可能吗?
最佳答案
这样的事情应该可以工作:
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);
}
...
}
你的监听器应该在 web.xml
中 Spring 的 ContextLoaderListener
之后声明。
关于java - 依赖注入(inject) servlet 监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5511152/