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

设置Spring ApplicationListener 的四种方式
注意前三种配置方式效果一样,而第四种,第五种配置方式无法监听 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中可以指定具体监控的事件类,通过方法参数指定事件类型,如果不指定则表示监控所有的事件

猜你喜欢

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