首页 » Java » Spring » 正文

Spring中的ApplicationListener和ServletContextListener的区别

监听器是典型的观察者设计模式的实现,Servlet和Spring中我们熟知的listeners包括:HttpSessionListenerServletContextListenerApplicationListener。

  • HttpSessionListener:是对javax.servlet.http.HttpSession(session)的监听;
  • ServletContextListener:是对javax.servlet.ServletContext(application)的监听;
  • ApplicationListener:是对Spring的ApplicationContext的监听。

其中,基于ServletContextListener的监听器要比基于ApplicationListener的监听器先执行。因为前者是Tomcat/Jetty容器启动后就执行,后者需要Spring应用初始化完成后才执行。

ServletContextListener

依赖于sevlet容器,需要配置web.xml(Spring Boot只需要配置@WebListener即可,并且使用@WebListener后,可以注入bean

  • public void contextInitialized(ServletContextEvent event):在ServletContext被创建时调用
  • public void contextDestroyed(ServletContextEvent event):在ServletContext被销毁时调用

如果是普通Spring应用,则还需要配置web.xml,比如:

ApplicationListener

依赖于Spring框架,在Spring启动时调用。在普通Spring应用中一般监听ContextRefreshedEvent事件。而在Spring Boot中可以监听多种事件,比如:

  • ApplicationStartedEvent:spring boot启动监听类
  • ApplicationEnvironmentPreparedEvent:环境事先准备
  • ApplicationPreparedEvent:上下文context准备时触发
  • ApplicationReadyEvent:上下文已经准备完毕的时候触发
  • ApplicationFailedEvent:该事件为spring boot启动失败时的操作

需要注意的是,在普通Spring环境中,基于ApplicationListener的监听器的onApplicationEvent方法可能会被执行多次,所以需要添加以下判断:

参考:

发表评论

*