dependency injectionservlet监听器

在我的Stripes应用程序中,我定义了以下类:

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener { private SomeService someService; private AnotherService anotherService; // remaining implementation omitted } 

此应用程序的服务层使用Spring来定义XML文件中的一些服务bean并将其连接在一起。 我想将实现SomeServiceAnotherService的bean注入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之后声明。

使用SpringBeanAutowiringSupport类稍微简单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); } ... }