依赖注入servlet监听器

Dón*_*nal 14 java spring stripes dependency-injection

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

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  private SomeService someService;

  private AnotherService anotherService;

  // remaining implementation omitted
} 
Run Code Online (Sandbox Code Playgroud)

此应用程序的服务层使用Spring来定义XML文件中的一些服务bean并将其连接在一起.我想注入实现SomeServiceAnotherService进入的bean,MyServletListener这可能吗?

axt*_*avt 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);
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

你的听众应该Spring的后宣布ContextLoaderListenerweb.xml.

  • @Don:`contextInitalized(ServletContextEvent)`在[`ServletContextListener`]上定义(http://download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener. HTML#contextInitialized(javax.servlet.ServletContextEvent)) (3认同)

Ond*_*zek 12

使用SpringBeanAutowiringSupport类更短更简单.
你所要做的就是:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
Run Code Online (Sandbox Code Playgroud)

所以使用axtavt的例子:

public class MyServletListener implements ServletContextListener, HttpSessionAttributeListener, HttpSessionListener {
    @Autowired
    private SomeService someService;        
    @Autowired
    private AnotherService anotherService; 

    public void contextInitialized(ServletContextEvent sce) {
        SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)