監聽器模式介紹
監聽器模式的要素
- 事件
- 監聽器
- 廣播器
- 觸發機制
SpringBoot監聽器實現
系統事件
事件發送順序
監聽器注冊
監聽器注冊和初始化器注冊流程類似
監聽器觸發機制
獲取監聽器列表核心流程:
通用觸發條件:
自定義監聽器實現
實現方式1
實現監聽器接口:
@Order(1)
public class FirstListener implements ApplicationListener<ApplicationStartedEvent> {@Overridepublic void onApplicationEvent(ApplicationStartedEvent event) {System.out.println("hello first");}
}
配置resources/META-INF/spring.factories
:
org.springframework.context.ApplicationListener=com.mooc.sb2.listener.FirstListener
實現方式2
啟動類中進行添加
@Order(2)
public class SecondListener implements ApplicationListener<ApplicationStartedEvent> {@Overridepublic void onApplicationEvent(ApplicationStartedEvent event) {System.out.println("hello second");}
}
@SpringBootApplication
@MapperScan("com.mooc.sb2.mapper")
public class Sb2Application {public static void main(String[] args) {
// SpringApplication.run(Sb2Application.class, args);SpringApplication springApplication = new SpringApplication(Sb2Application.class);
// springApplication.addInitializers(new SecondInitializer());springApplication.addListeners(new SecondListener());springApplication.run(args);}}
實現方式3
properties文件中進行配置
同初始化器一樣,同樣需要注意,這種方式的Order會失效,跟前面兩種方式相比始終都是最先加載
@Order(3)
public class ThirdListener implements ApplicationListener<ApplicationStartedEvent> {@Overridepublic void onApplicationEvent(ApplicationStartedEvent event) {System.out.println("hello third");}}
key值context.listener.classes
value值: listener類的全類名
context.listener.classes=com.mooc.sb2.listener.ThirdListener
實現方式4
自定義制定監聽器對哪一類事件感興趣
@Order(4)
public class FourthListener implements SmartApplicationListener {@Overridepublic boolean supportsEventType(Class<? extends ApplicationEvent> eventType) {return ApplicationStartedEvent.class.isAssignableFrom(eventType) || ApplicationPreparedEvent.class.isAssignableFrom(eventType);}@Overridepublic void onApplicationEvent(ApplicationEvent event) {System.out.println("hello fourth");}
}
配置resources/META-INF/spring.factories
:
org.springframework.context.ApplicationListener=com.mooc.sb2.listener.FourthListener
啟動后會發現"hello fourth"會被打印兩次,因為兩個事件都觸發了,所以打印了兩遍
面試題
- 介紹一下監聽器模式?
-
- 結合源碼圖和四要素進行回答
- SpringBoot關于監聽器相關的實現類有哪些?
-
- 可以通過spring.factories文件去看具體的實現類有哪些
- SpringBoot框架有哪些框架事件以及它們的發送順序?
-
- 參考上面事件發送順序流程圖
- 介紹一下監聽事件的觸發機制?
-
- 圍繞著監聽器的加載注冊,以及如何判斷出監聽器對某一個事件感興趣進行作答
- 如何自定義實現系統監聽器及注意事項?
- 實現
ApplicationListener
接口與SmartApplicantionListener
接口的區別?
-
ApplicationListener
只能指定對某一類事件的監聽,而SmartApplicantionListener
可以實現指定對多類事件的監聽