【问题标题】:How to inject dependencies into HttpSessionListener, using Spring?如何使用 Spring 将依赖项注入 HttpSessionListener?
【发布时间】:2011-01-26 20:39:05
【问题描述】:

如何在没有调用的情况下使用 Spring 将依赖项注入 HttpSessionListener,例如 context.getBean("foo-bar")

【问题讨论】:

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


    【解决方案1】:

    由于 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 在您的应用程序上下文中存在,就会导致侦听器注册到容器中

    【讨论】:

    • 因此,通过这种方法,您能否从 web.xml 中的 部分中完全删除“MyHttpSessionListener”?
    • 是的,没错。使用这种方法,您甚至不需要 web.xml。
    • 在 Spring 5.x 中你不需要 ApplicationContextAware 接口。 @component 正在注册监听器,看起来很好。
    【解决方案2】:

    您可以在 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);
        }
    
        ...
    }
    

    【讨论】:

    • 这很好的解决方案,我想知道为什么Spring本身没有这样的DelegationListener。
    • 这不能与 DelegatingFilterProxy 一起工作的一个原因是无法从 web.xml 传递参数。你最终不得不假设一个 bean 名称,然后你只能支持一个委托监听器(除非有一种我没有看到的方法)。
    • 这是一个很好的答案!
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-12
      • 1970-01-01
      • 2013-12-26
      • 1970-01-01
      • 2012-07-16
      • 2012-08-22
      • 1970-01-01
      相关资源
      最近更新 更多