Search code examples
springservletsdependency-injectionhttpsessionservlet-listeners

How to inject dependencies into HttpSessionListener, using Spring?


How to inject dependencies into HttpSessionListener, using Spring and without calls, like context.getBean("foo-bar") ?


Solution

  • Since the Servlet 3.0 ServletContext has an "addListener" method, instead of adding your listener in your web.xml file you could add through code like so:

    @Component
    public class MyHttpSessionListener implements javax.servlet.http.HttpSessionListener, ApplicationContextAware {
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if (applicationContext instanceof WebApplicationContext) {
                ((WebApplicationContext) applicationContext).getServletContext().addListener(this);
            } else {
                //Either throw an exception or fail gracefully, up to you
                throw new RuntimeException("Must be inside a web application context");
            }
        }           
    }
    

    which means you can inject normally into the "MyHttpSessionListener" and with this, simply the presence of the bean in your application context will cause the listener to be registered with the container