如何使用 Spring 将依赖项注入 HttpSessionListener?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2433321/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to inject dependencies into HttpSessionListener, using Spring?
提问by Illarion Kovalchuk
How to inject dependencies into HttpSessionListener, using Spring and without calls, like context.getBean("foo-bar")?
如何使用 Spring 而不调用将依赖项注入 HttpSessionListener,例如context.getBean("foo-bar")?
回答by Yinzara
Since the Servlet 3.0 ServletContext has an "addListener" method, instead of adding your listener in your web.xml file you could add through code like so:
由于 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");
}
}
}
which means you can inject normally into the "MyHttpSessionListener" and with this, simply the presence of the bean in your application context will cause the listener to be registered with the container
这意味着您可以正常注入到“MyHttpSessionListener”中,这样,应用程序上下文中 bean 的存在将导致侦听器向容器注册
回答by axtavt
You can declare your HttpSessionListeneras a bean in Spring context, and register a delegation proxy as an actual listener in web.xml, something like this:
您可以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);
}
...
}
回答by Teixi
With Spring 4.0 but also works with 3, I implemented the example detailed below, listening to ApplicationListener<InteractiveAuthenticationSuccessEvent>and injecting the HttpSessionhttps://stackoverflow.com/a/19795352/2213375
使用 Spring 4.0 但也适用于 3,我实现了下面详述的示例,监听ApplicationListener<InteractiveAuthenticationSuccessEvent>并注入HttpSessionhttps://stackoverflow.com/a/19795352/2213375

