如何使用Spring将依赖项注入HttpSessionListener? [英] How to inject dependencies into HttpSessionListener, using Spring?
问题描述
如何使用Spring和没有调用注入HttpSessionListener,如 context.getBean(foo-bar)
?
How to inject dependencies into HttpSessionListener, using Spring and without calls, like context.getBean("foo-bar")
?
推荐答案
由于Servlet 3.0 ServletContext有一个addListener方法,而是将您的监听器添加到web.xml文件中,您可以通过以下代码添加:
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:
@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就可以使监听器向容器注册。
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
这篇关于如何使用Spring将依赖项注入HttpSessionListener?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!