14

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

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  private SomeService someService;

  private AnotherService anotherService;

  // remaining implementation omitted
} 

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

4

2 回答 2

25

像这样的东西应该工作:

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

    ...
}

你的监听器应该在 Spring 的ContextLoaderListenerin之后声明web.xml

于 2011-04-01T09:04:06.020 回答
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);
    }

    ...
}
于 2013-10-30T13:25:40.590 回答