在使用Spring框架開發時, 有時我們需要在spring容器初始化完成後做一些操作, 那麼我們可以通過自定義ApplicationListener 來實現.
自定義監聽器
@Component
public class MyApplicationListener implements ApplicationListener<ContextRefreshedEvent> {
@Override
public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
// 獲取spring 上下文
ApplicationContext applicationContext = contextRefreshedEvent.getApplicationContext();
// do your work...
}
源碼分析
- springboot 啓動應用, 執行 SpringApplication.run(String… args) 方法
- run方法中執行完初始化上下文方法後, 會執行this.refreshContext方法, 刷新
- 經過一堆方法跳轉, 執行 AbstractApplicationContextl類的publishEvent(Object event, @Nullable ResolvableType eventType) 方法
- 然後執行 SimpleApplicationEventMulticaster.multicastEvent(ApplicationEvent event, @Nullable ResolvableType eventType)
- 然後依次執行所有監聽器的onApplicationEvent()方法
// 遍歷所有ApplicationListeners, 依次執行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);
}
}
}