如何使用Spring将依赖项注入HttpSessionListener?

时间:2010-03-12 14:24:43

标签: spring servlets dependency-injection httpsession servlet-listeners

如何使用Spring和没有调用(例如context.getBean("foo-bar"))将依赖项注入HttpSessionListener?

3 个答案:

答案 0 :(得分:27)

由于Servlet 3.0 ServletContext有一个“addListener”方法,而不是在你的web.xml文件中添加你的监听器,你可以通过这样的代码添加:

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

这意味着您可以正常注入“MyHttpSessionListener”,只需在应用程序上下文中存在bean就会导致监听器向容器注册

答案 1 :(得分:8)

您可以在Spring上下文中将HttpSessionListener声明为bean,并在web.xml中将委派代理注册为实际侦听器,如下所示:

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

    ...
}

答案 2 :(得分:1)

使用Spring 4.0但也适用于3,我实现了下面详述的示例,听取ApplicationListener<InteractiveAuthenticationSuccessEvent>并注入HttpSession https://stackoverflow.com/a/19795352/2213375

相关问题