spring boot 監(jiān)聽容器啟動(dòng)代碼實(shí)例
在使用Spring框架開發(fā)時(shí), 有時(shí)我們需要在spring容器初始化完成后做一些操作, 那么我們可以通過自定義ApplicationListener 來實(shí)現(xiàn).
自定義監(jiān)聽器
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// 獲取spring 上下文
ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
// do your work...
}
源碼分析
springboot 啟動(dòng)應(yīng)用, 執(zhí)行 SpringApplication.run(String… args) 方法
run方法中執(zhí)行完初始化上下文方法后, 會(huì)執(zhí)行this.refreshContext方法, 刷新
經(jīng)過一堆方法跳轉(zhuǎn), 執(zhí)行 AbstractApplicationContextl類的publishEvent(Object event, @Nullable ResolvableType eventType) 方法
然后執(zhí)行 SimpleApplicationEventMulticaster.multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType)
然后依次執(zhí)行所有監(jiān)聽器的onApplicationEvent()方法
// 遍歷所有ApplicationListeners, 依次執(zhí)行ApplicationListener 的onApplicationEvent()方法
public void multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType) {
ResolvableType type = eventType != null ? eventType : this.resolveDefaultEventType(event);
Iterator var4 = this.getApplicationListeners(event, type).iterator();
while(var4.hasNext()) {
ApplicationListener<?> listener = (ApplicationListener)var4.next();
Executor executor = this.getTaskExecutor();
if (executor != null) {
executor.execute(() -> {
this.invokeListener(listener, event);
});
} else {
this.invokeListener(listener, event);
}
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot中Getmapping獲取參數(shù)的實(shí)現(xiàn)方式
這篇文章主要介紹了springboot中Getmapping獲取參數(shù)的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解
這篇文章主要為大家介紹了SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05
SpringMVC如何自定義響應(yīng)的HTTP狀態(tài)碼
這篇文章主要介紹了SpringMVC如何自定義響應(yīng)的HTTP狀態(tài)碼,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-11-11
Java判斷一個(gè)字符串是不是一個(gè)數(shù)字的解決思路
這篇文章主要給大家介紹了關(guān)于Java判斷一個(gè)字符串是不是一個(gè)數(shù)字的解決思路,判斷一個(gè)字符串是否為數(shù)字是Java開發(fā)中很常見的業(yè)務(wù)需求,實(shí)現(xiàn)這個(gè)判斷有很多種方式,需要的朋友可以參考下2023-08-08
java構(gòu)造http請(qǐng)求的幾種方式(附源碼)
本文主要介紹了java構(gòu)造http請(qǐng)求的幾種方式,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02
jmeter設(shè)置全局變量與正則表達(dá)式提取器過程圖解
這篇文章主要介紹了jmeter設(shè)置全局變量與正則表達(dá)式提取器過程圖解,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-10-10

