從出現時間上看:
org.springframework.context.ApplicationListener,Spring 1.0開始出現
org.springframework.context.ApplicationContextInitializer,Spring 3.1開始出現
org.springframework.boot.SpringApplicationRunListener,Spring boot 1.0.0開始出現
org.springframework.boot.BootstrapRegistryInitializer,Spring boot2.4.5開始出現
從執行時間上看,先后順序為:
BootstrapRegistryInitializer
SpringApplicationRunListener
ApplicationContextInitializer
ApplicationListener
從執行方式上看:
BootstrapRegistryInitializer的執行在run()方法中createBootstrapContext()方法中調用。
SpringApplicationRunListener的執行發生在run()方法中SpringApplicationRunListeners類手動調用。
ApplicationContextInitializer的執行發生在run()方法中的prepareContext()方法中。
ApplicationListener的執行發生在SpringApplicationRunListeners類手動調用時,會多次發生,由SpringApplicationRunListener的實現類EventPublishingRunListener去廣播給ApplicationListener。
從作用上看:
BootstrapRegistryInitializer,沒有自定義實現,
SpringApplicationRunListener,有大量自定義實現,分發時間觸發ApplicationListener執行
ApplicationContextInitializer,有大量自定義實現,
ApplicationListener,有大量自定義實現,
設計分析
Spring時期,就有了 ApplicationListener這個監聽器,用于給開發者擴展插件,它可以接受多個階段的事件,開發者可以判斷事件類型來決定是否要執行擴展邏輯。
在Spring boot中,通過SpringApplicationRunListeners這個控制類,來在不同階段調用執行所有的SpringApplicationRunListener監聽器,其中有個監聽器EventPublishingRunListener,他能廣播所有相關事件給ApplicationListener監聽器。
事件的分類
org.springframework.context.ApplicationEvent,spring1.0出現的,是下面事件的父類
org.springframework.context.event.ApplicationContextEvent,是spring 2.5出現的
org.springframework.boot.context.event.SpringApplicationEvent,是spring boot 1.0.0出現的