Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dependency inject servlet listener

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?

like image 638
Dónal Avatar asked Apr 01 '11 08:04

Dónal


2 Answers

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.

like image 100
axtavt Avatar answered Oct 29 '22 04:10

axtavt


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

    ...
}
like image 31
Ondrej Bozek Avatar answered Oct 29 '22 05:10

Ondrej Bozek