Spring中的ApplicationListener和ServletContextListener的区别

ServletContextListener:是对javax.servlet.ServletContext(application)的监听,Tomcat/Jetty容器启动后就执行;

ApplicationListener:是对Spring的ApplicationContext的监听,Spring应用初始化完成后。

ServletContextListener:

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

  2、需要重写contextInitialized方法,public void contextInitialized(ServletContextEvent event),在ServletContext被创建时调用

  3、public void contextDestroyed(ServletContextEvent event):在ServletContext被销毁时调用

ApplicationListener:

  1、依赖于Spring框架,在Spring启动时调用。在普通Spring应用中一般监听ContextRefreshedEvent事件。

  2、重写onApplicationEvent方法,public void onApplicationEvent(ContextRefreshedEvent event) ,用于容器初始化完成之后,执行需要处理的一些操作

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

  if(event.getApplicationContext().getParent() == null)

原文地址:https://www.cnblogs.com/wangsizheng/p/13690039.html