如何在不使用调用的情况下使用Spring将依赖项注入HttpSessionListener中context.getBean("foo-bar")?
HttpSessionListener中context.getBean("foo-bar")
由于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,就会使侦听器注册到容器中