代码之家  ›  专栏  ›  技术社区  ›  Illarion Kovalchuk

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

  •  23
  • Illarion Kovalchuk  · 技术社区  · 15 年前

    如何向HttpSessionListener注入依赖项,使用Spring和不调用,比如 context.getBean("foo-bar")

    3 回复  |  直到 11 年前
        1
  •  29
  •   yop83    10 年前

    由于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,就可以使用容器注册侦听器

        2
  •  8
  •   axtavt    15 年前

    你可以申报 HttpSessionListener 作为Spring上下文中的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);
        }
    
        ...
    }
    
        3
  •  1
  •   Community CDub    7 年前

    使用Spring4.0,但也可以使用3,我实现了下面详细介绍的示例,如下所示 ApplicationListener<InteractiveAuthenticationSuccessEvent> 然后注射 HttpSession https://stackoverflow.com/a/19795352/2213375