spring boot 監(jiān)聽容器啟動代碼實例
在使用Spring框架開發(fā)時, 有時我們需要在spring容器初始化完成后做一些操作, 那么我們可以通過自定義ApplicationListener 來實現(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 啟動應(yīng)用, 執(zhí)行 SpringApplication.run(String… args) 方法
run方法中執(zhí)行完初始化上下文方法后, 會執(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); } } }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot中Getmapping獲取參數(shù)的實現(xiàn)方式
這篇文章主要介紹了springboot中Getmapping獲取參數(shù)的實現(xiàn)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-05-05SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解
這篇文章主要為大家介紹了SpringMVC域?qū)ο蠊蚕頂?shù)據(jù)示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-05-05SpringMVC如何自定義響應(yīng)的HTTP狀態(tài)碼
這篇文章主要介紹了SpringMVC如何自定義響應(yīng)的HTTP狀態(tài)碼,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-11-11jmeter設(shè)置全局變量與正則表達(dá)式提取器過程圖解
這篇文章主要介紹了jmeter設(shè)置全局變量與正則表達(dá)式提取器過程圖解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2019-10-10