Ill*_*huk 24 spring servlets dependency-injection httpsession servlet-listeners
如何使用Spring和没有调用将依赖项注入HttpSessionListener,如context.getBean("foo-bar")?
Yin*_*ara 27
由于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");
}
}
}
Run Code Online (Sandbox Code Playgroud)
这意味着您可以正常注入"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);
}
...
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21376 次 |
| 最近记录: |