【问题】实现ApplicationListener接口和实现SmartApplicationListener 接口?
实现ApplicationListener接口针对单一事件监听
实现SmartApplicationListener 接口针对多种事件监听
其它注意:
Order值越小越优先执行
使用application.properties中定义的优于其它方式
【问题】如何自定义监听器?
一、实现方式1
1、创建监听器类FirstListener.java
@Order(1) public class FirstListener implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent event) { System.out.println("hello, first listener"); } }
2、在spring.factories文件中增加配置监听器
org.springframework.context.ApplicationListener=com.example.demo.listener.FirstListener
3、运行查看效果
二、实现方式2
1、创建监听器类
@Order(2) public class SecondListener implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent event) { System.out.println("hello, second listener"); } }
2、实例化SpringApplication,然后增加监听器
@SpringBootApplication @MapperScan("com.example.demo.mapper") public class Sb2Application { public static void main(String[] args) { SpringApplication springApplication = new SpringApplication(Sb2Application.class); springApplication.addListeners(new SecondListener()); springApplication.run(args); } }
3、运行
三、实现方式3
1、创建监听器类
@Order(3) public class ThirdListener implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent event) { System.out.println("hello, third listener"); } }
2、在application.propeties 文件中配置如下
3、运行
第三个监听器Order为3,但是却最早打印出来。原理类似于初始化器。DelegatingApplicationListener类里定义的Order为0
四、实现方式4
1、创建监听器类
@Order(4) public class FourthListener implements SmartApplicationListener { @Override public boolean supportsEventType(Class<? extends ApplicationEvent> eventType) { return ApplicationStartedEvent.class.isAssignableFrom(eventType) || ApplicationPreparedEvent.class.isAssignableFrom(eventType); } @Override public void onApplicationEvent(ApplicationEvent event) { System.out.println("hello fourth listener"); } }
设置感兴趣的事件为ApplicationStartedEvent和ApplicationPreparedEvent
2、以追加的方式在application.properties配置
3、运行
可以发现打印了两次,因为它对ApplicationStartedEvent和ApplicationPreparedEvent两种事件感兴趣。
原文地址:https://www.cnblogs.com/linlf03/p/12332844.html
时间: 2024-11-24 22:34:18