ServletContextListener:是对javax.servlet.ServletContext(application)的监听。
ApplicationListener:是对Spring的ApplicationContext的监听。
HttpSessionListener:是对javax.servlet.http.HttpSession(session)的监听。
HttpSessionAttributeListener接口:对session的属性监听。
基于ServletContextListener的监听器要比基于ApplicationListener的监听器先执行。因为前者是Tomcat/Jetty容器启动后就执行,后者需要Spring应用初始化完成后才执行。
ServletContextListener
ServletContextAttributeListener
ServletRequestListener
每一个 Web 应用程序含有一个Context,被Web应用内的各个程序共享。
public interface ServletContextListener extends EventListener {
public void contextInitialized(ServletContextEvent sce);
public void contextDestroyed(ServletContextEvent sce);
}
如果是普通Spring应用,则还需要配置web.xml
<listener>
<listener-class>com.my.listener.TestListener</listener-class>
</listener>
如果是SpringBoot应用,则使用@WebListener注解。
在Springboot web 应用启动代码中添加@ServletComponentScan注解。
添加@ServletComponentScan注解后Servlet、Filter、Listener 可以直接通过 @WebServlet、@WebFilter、@WebListener 注解自动注册,无需其他代码。
如果@Autowired注入bean,可能是null。
@WebListener
public class MyServletContextListener implements ServletContextListener{
public void contextInitialized(ServletContextEvent sce){
//这样的话,@Autowired注入bean就可以使用了
WebApplicationContextUtils.getRequiredWebApplicationContext(sce.getServletContext())
.getAutowireCapableBeanFactory().autowireBean(this);
System.out.println("dao++++"+dao.count());
}
public void contextDestroyed(ServletContextEvent sce);
@Autowired
private MyDao dao;
}
ApplicationListener
在普通Spring环境中,基于ApplicationListener的监听器的onApplicationEvent方法可能会被执行多次。
在web 项目中(spring mvc),系统会存在两个容器,一个是root application context,另一个就是我们自己的 projectName-servlet context(作为root application context的子容器)。
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if(event.getApplicationContext().getParent() == null){
//需要执行的逻辑代码
}
}