如何使用Spring和不来电,就像context.getBean("foo-bar")到依赖注入HttpSessionListener,?

有帮助吗?

解决方案

由于在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的存在会导致听者与容器中注册

其他提示

您可以声明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);
    }

    ...
}

使用弹簧4.0但还与3,我实现下面详细描述的例子中,收听和ApplicationListener<InteractiveAuthenticationSuccessEvent>注入HttpSession https://开头stackoverflow.com/a/19795352/2213375

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top