14

In my Stripes app I define the following class:

MyServletListener implements ServletContextListener, HttpSessionListener, HttpSessionAttributeListener {

  private SomeService someService;

  private AnotherService anotherService;

  // remaining implementation omitted
} 

The service layer of this app uses Spring to define and wire together some service beans in an XML file. I would like to inject the beans that implement SomeService and AnotherService into MyServletListener, is this possible?

Dónal
  • 185,044
  • 174
  • 569
  • 824

2 Answers2

25

Something like this should work:

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

    ...
}

Your listener should be declared after Spring's ContextLoaderListener in web.xml.

Dónal
  • 185,044
  • 174
  • 569
  • 824
axtavt
  • 239,438
  • 41
  • 511
  • 482
  • 3
    @Don: `contextInitalized(ServletContextEvent)` is defined on [`ServletContextListener`](http://download.oracle.com/docs/cd/E17802_01/products/products/servlet/2.3/javadoc/javax/servlet/ServletContextListener.html#contextInitialized(javax.servlet.ServletContextEvent)) – ig0774 Apr 01 '11 at 13:03
  • 1
    Important : In web.xml ContextLoaderListener must be loaded before MyServletListener. – Nico Apr 15 '13 at 17:53
12

Little bit shorter and simpler is to use SpringBeanAutowiringSupport class.
Than all you have to do is this:

SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);

So using example from axtavt:

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

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

    ...
}
Ondrej Bozek
  • 10,987
  • 7
  • 54
  • 70