依赖注入servlet监听器

时间:2011-04-01 08:55:17

标签: java spring dependency-injection stripes

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

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  private SomeService someService;

  private AnotherService anotherService;

  // remaining implementation omitted
} 

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

2 个答案:

答案 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);
    }

    ...
}