溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

spring boot 中怎么監(jiān)聽容器啟動(dòng)

發(fā)布時(shí)間:2021-06-15 15:10:12 來(lái)源:億速云 閱讀:364 作者:Leah 欄目:編程語(yǔ)言

這篇文章給大家介紹spring boot 中怎么監(jiān)聽容器啟動(dòng),內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對(duì)大家能有所幫助。

自定義監(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)過(guò)一堆方法跳轉(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);
    }
  }

}

關(guān)于spring boot 中怎么監(jiān)聽容器啟動(dòng)就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,可以學(xué)到更多知識(shí)。如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI