SpringBoot中配置ApplicationListener 监听器的几种方式

转载自 https://blog.csdn.net/u013202238/article/details/83215311

设置Spring ApplicationListener 的6种方式
第一种无法监听
org.springframework.boot.context.event.ApplicationStartedEvent
第四种,第五种配置方式无法监听
org.springframework.boot.context.event.ApplicationStartedEvent
org.springframework.boot.context.event.ApplicationEnvironmentPreparedEvent
org.springframework.boot.context.event.ApplicationPreparedEvent

1 在application.yml或者在application.properties配置文件中通过context.listener.classes配置

2 在resources目录下新建META-INF文件夹并新建spring.factories文件通过org.springframework.context.ApplicationListener配置

3 在启动main函数中通过SpringApplication配置
SpringApplication springApplication = new SpringApplication(null);
springApplication.addListeners(你的监听器);

4 使用@Configuration 注解配置,同时可以配合@Order(-100)设置优先级

5 使用@EventListener 注解配置在bean中定义任意方法并使用该注解, 注解属性class中可以指定具体监控的事件类,通过方法参数指定事件类型,如果不指定则表示监控所有的事件

6 通过实现接口org.springframework.context.ApplicationContextInitializer,得到context后通过编程式,设置监听器

原文地址:https://www.cnblogs.com/lansetuerqi/p/14979494.html