天天看點

Springboot生命周期

application.properties中增加

實作接口ApplicationListener

ApplicationContextInitializedEvent:當 SpringApplication 啟動并且準備好 ApplicationContext,并且在加載任何 bean 定義之前調用了 ApplicationContextInitializers 時釋出的事件。對應的生命周期方法是contextPrepared()。

ApplicationPreparedEvent:它是SpringBoot上下文 context 建立完成是釋出的事件;但此時 spring 中的 bean 還沒有完全初始化完成,因為後面還要refreshContext。這裡可以将上下文傳遞出去做一些額外的操作。但是在該監聽器中是無法擷取自定義 bean 并進行操作的。對應的生命周期方法是 contextLoaded()。

ApplicationStartedEvent:這個事件是在 2.0 版本才引入的;具體釋出是在應用程式上下文重新整理之後,調用任何 ApplicationRunner 和 CommandLineRunner 運作程式之前。

SpringApplicationRunListeners:是一個集合類,内部包含一個 log 和包含 SpringApplicationRunListener 的 List。而 SpringApplicationRunListener 主要是監聽 SpringApplication 對象的,裡面的方法都定義了在何時調用 SpringApplicationRunListener 的各種方法,它的實作類是EventPublishingRunListener。它就是一個ApplicationListener的代理。springboot啟動的幾個主要過程的監聽通知都是通過他來進行回調,它的生命周期就是從開始啟動,到啟動結束。

    下面的每一個方法 SpringApplicationRunListener 都把其包裝成一個事件,在spring容器還未成功 refreshed 之前都是使用SimpleApplicationEventMulticaster 去尋找對該事件感興趣的ApplicationListener,然後調用其onApplicationEvent方法

starting:當SpringApplication對象的run方法剛啟動的時候(依靠SimpleApplicationEventMulticaster),對應的事件:ApplicationStartingEvent

environmentPrepared:在environment Prepared 但是spring容器還未建立的時候(依靠SimpleApplicationEventMulticaster),對應的事件:ApplicationPreparedEvent

contextPrepared:當spring容器已經建立且準備好了,(目前是空的實作),這時候environment資源還沒初始化完成。

contextLoaded:當spring容器已經loaded 且未refreshContext 。這個時候environment資源也初始化完成。load就是将我們的primaryClass注冊到spring容器中,(依靠SimpleApplicationEventMulticaster) 同時将之前擷取到的ApplicationListener都加入到spring容器中,此時如果ApplicationListener還是ApplicationContextAware的也要調用其setApplicationContext方法。對應的事件:ApplicationPreparedEvent

started:spring容器已經重新整理過且應用已經啟動,但是CommandLineRunners和ApplicationRunners還未調用,直接通過spring容器自己發送(因為ApplicationListener已經加入spring容器),對應的事件:ContextStartedEvent

running:我們已經調用了CommandLineRunners,直接通過spring容器自己發送(因為ApplicationListener已經加入spring容器),對應的事件:ApplicationReadEvent

failed:當異常發生的時候就調用這個,如果spring容器沒有loaded 或者沒有激活就使用SimpleApplicationEventMulticaster,否則還是依靠spring容器自己。對應該事件:ApplicationFailedEvent

下一篇: Vue生命周期