How to inject dependencies into HttpSessionListener, using Spring?

只谈情不闲聊 提交于 2019-12-28 02:06:14

问题


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


回答1:


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




回答2:


You can declare your HttpSessionListener as a bean in Spring context, and register a delegation proxy as an actual listener in web.xml, something like this:

public class DelegationListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent se) {
        ApplicationContext context = 
            WebApplicationContextUtils.getWebApplicationContext(
                se.getSession().getServletContext()
            );

        HttpSessionListener target = 
            context.getBean("myListener", HttpSessionListener.class);
        target.sessionCreated(se);
    }

    ...
}



回答3:


With Spring 4.0 but also works with 3, I implemented the example detailed below, listening to ApplicationListener<InteractiveAuthenticationSuccessEvent> and injecting the HttpSession https://stackoverflow.com/a/19795352/2213375



来源:https://stackoverflow.com/questions/2433321/how-to-inject-dependencies-into-httpsessionlistener-using-spring

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!