【发布时间】:2011-01-26 20:39:05
【问题描述】:
如何在没有调用的情况下使用 Spring 将依赖项注入 HttpSessionListener,例如 context.getBean("foo-bar") ?
【问题讨论】:
标签: spring servlets dependency-injection httpsession servlet-listeners
如何在没有调用的情况下使用 Spring 将依赖项注入 HttpSessionListener,例如 context.getBean("foo-bar") ?
【问题讨论】:
标签: spring servlets dependency-injection httpsession servlet-listeners
由于 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 在您的应用程序上下文中存在,就会导致侦听器注册到容器中
【讨论】:
您可以在 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 4.0 但也适用于 3,我实现了下面详述的示例,监听 ApplicationListener<InteractiveAuthenticationSuccessEvent> 并注入 HttpSession https://stackoverflow.com/a/19795352/2213375
【讨论】: