由于Servlet 3.0 ServletContext具有“ addListener”方法,因此可以通过如下代码添加而不是在web.xml文件中添加侦听器:
@Componentpublic 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,就会使侦听器注册到容器中



