SpringBoot的多種事件監聽機制

来源:https://www.cnblogs.com/chafry/archive/2022/10/18/16801190.html
-Advertisement-
Play Games

前置配置 # META-INF/spring.factories文件配置 # ApplicationContextInitializer org.springframework.context.ApplicationContextInitializer=com.test.springbootdemo ...


前置配置

# META-INF/spring.factories文件配置
# ApplicationContextInitializer
org.springframework.context.ApplicationContextInitializer=com.test.springbootdemo.eventListeners.MyApplicationContextInitializer
# ApplicationListener
org.springframework.context.ApplicationListener=com.test.springbootdemo.eventListeners.MyApplicationListener
# SpringApplicationRunListener
org.springframework.boot.SpringApplicationRunListener=com.test.springbootdemo.eventListeners.MySpringApplicationRunListener

 

ApplicationContextInitializer介面

代碼示例

public class MyApplicationContextInitializer implements ApplicationContextInitializer {
    //run方法this.prepareContext觸發
    //進一步則是this.applyInitializers
    //在進一步則是initializer.initialize(context);
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        System.out.println("ApplicationContextInitializer.....initialize");
    }
}

說明

  1.由於觸發階段在於準備容器的時候,所以添加@Component註解是不會起作用的,應為@Component註解需要在容器刷新時候才會起到作用。

 

ApplicationListener介面

代碼示例

public class MyApplicationListener implements ApplicationListener {
    //run方法listeners.starting,觸發第一次
    //run方法this.prepareEnvironment,觸發第二次
    //即進一步,listeners.environmentPrepared
    //run方法this.prepareContext,觸發第三次與觸發第四次
    //進一步則是listeners.contextPrepared(context);觸發第三次
    // listeners.contextLoaded(context);觸發第四次
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextStartedEvent){
            System.out.println("ContextStartedEvent1.....run()");
        }

        System.out.println("Event1.....run()");

    }
}

@Component
public class MyApplicationListener2 implements ApplicationListener {
    //容器refresh()的時候觸發
    //進一步finishRefresh();
    //再進一步getLifecycleProcessor().onRefresh();
    @Override
    public void onApplicationEvent(ApplicationEvent event) {
        if (event instanceof ContextStartedEvent){
            System.out.println("ContextStartedEvent2.....run()");
        }

        System.out.println("Event2.....run()");
    }
}

說明

  1.存在兩種註冊方式:

    1)@Component註解註冊,這種需要在容器刷新後的finishRefresh()方法裡面觸發,然後監聽到全部事件

    2)配置文件註冊,這種會在SpringBoot中開啟listeners,讓listeners準備環境,準備容器等都會觸發。包括容器刷新後的finishRefresh()方法裡面都會觸發【包括了註解修飾的部分】

 

ApplicationRunner介面

代碼示例

@Component
public class MyApplicationRunner implements ApplicationRunner {
    //run方法this.callRunners,第一次觸發
    //進一步,this.callRunner
    //在進一步,runner.run(args);
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println("ApplicationRunner.....run()");
    }
}

說明

  1.這種只能在容器啟動後進行觸發

  2.與CommandLineRunner介面其實並沒有很大差別,都在同一個方法內被調用,調用同一個觸發方法。但是會優於CommandLineRunner被調用。

 

CommandLineRunner介面

代碼示例

@Component
public class MyCommandLineRunner implements CommandLineRunner {
    //run方法this.callRunners,第一次觸發
    //進一步,this.callRunner
    //在進一步,runner.run(args);
    @Override
    public void run(String... args) throws Exception {
        System.out.println("CommandLineRunner.....run()");
    }
}

說明

  1.這種只能在容器啟動後進行觸發

  2.與ApplicationRunner介面其實並沒有很大差別,都在同一個方法內被調用,調用同一個觸發方法。但是會晚於ApplicationRunner被調用。

 

SpringApplicationRunListener介面

代碼示例

public class MySpringApplicationRunListener implements SpringApplicationRunListener {
    public MySpringApplicationRunListener(SpringApplication springApplication, String[] arg) {
    }

    //run方法listeners.starting觸發
    @Override
    public void starting(ConfigurableBootstrapContext bootstrapContext) {
        System.out.println("SpringApplicationRunListener.....starting()");
    }

    //run方法this.prepareEnvironment觸發
    //進一步listeners.environmentPrepared
    @Override
    public void environmentPrepared(ConfigurableBootstrapContext bootstrapContext, ConfigurableEnvironment environment) {
        System.out.println("SpringApplicationRunListener.....environmentPrepared()");
    }

    //run方法this.prepareContext觸發
    //進一步listeners.contextPrepared(context);
    @Override
    public void contextPrepared(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener.....contextPrepared()");
    }

    //run方法this.prepareContext觸發
    //進一步listeners.contextLoaded(context);
    @Override
    public void contextLoaded(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener.....contextLoaded()");
    }

    //run方法listeners.started(context, timeTakenToStartup);觸發
    @Override
    public void started(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("SpringApplicationRunListener.....started()");
    }

    @Override
    public void started(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener.....started()");
    }

    //run方法listeners.ready(context, timeTakenToReady);觸發
    @Override
    public void ready(ConfigurableApplicationContext context, Duration timeTaken) {
        System.out.println("SpringApplicationRunListener.....ready()");
    }

    @Override
    public void running(ConfigurableApplicationContext context) {
        System.out.println("SpringApplicationRunListener.....running()");
    }

    @Override
    public void failed(ConfigurableApplicationContext context, Throwable exception) {
        System.out.println("SpringApplicationRunListener.....failed()");
    }
}

說明

  1.這個比較有意思在容器Refresh()前後都會觸發,包括各種處理環境,準備容器等步驟。


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 下一代 IDE 的形態究竟是什麼呢?VS Code For Web 試圖回答這個問題。 背景 眾所周知,VS Code 是當前工業界最優秀的代碼編輯器之一。它由《設計模式》的作者 Erich Gamma 領導開發,因此,它的設計架構在很多地方十分精妙,近些年已經成為了各家競相模仿學習的對象。 儘管 ...
  • 百度ueditor使用方法 下載地址:https://github.com/fex-team/ueditor html <textarea id="content" type="text/plain" name="content" lay-verify="required"></textarea> ...
  • 摘要:本文將淺析nextTick的作用、使用場景和背後的原理實現,希望對大家有所幫助。 本文分享自華為雲社區《Vue 中的 nextTick 有什麼作用?》,作者:CoderBin。 一、什麼是nextTick 先看看官方對其的定義: 在下次 DOM 更新迴圈結束之後執行延遲回調。在修改數據之後立即 ...
  • 結論:76版本(至少)之前的Chrome,<video>poster屬性只在created中生效 需求描述:輸入視頻分:秒格式【00:00】,視頻封面顯示為輸入時間的視頻截圖 方案:由輸入分:秒修改為增加截取按鈕,點擊時暫停播放,獲取當前播放時間,資料庫保存為double;展示時通過canves繪製 ...
  • 一、HTTP和HTTPS協議的概念及區別 1.HTTP 概念 HTTP即超文本運輸協議,是實現網路通信的一種規範,它定義了客戶端和伺服器之間交換報文的格式和方式,預設使用 80 埠。它使用 TCP 作為傳輸層協議,保證了數據傳輸的可靠性。 HTTP是一個傳輸協議,即將數據由A傳到B或將B傳輸到A, ...
  • 作為一個程式員如果你想要找到你心儀的工作,不可避免的就會問到很多八股文,雖然有的和工作沒有半毛錢關係,但是你如果想要通過面試還必須得會。所以我最近開始總結一些面試題,一是為了加強自己的理解能夠找到一份好的工作,二是為了儘可能的幫助更多的小伙伴能夠快速掌握相關知識或者順利通過面試🎉。 本篇文章介紹了 ...
  • 觀察者模式是使用頻率最高的設計模式之一,用於建立對象與對象之間的依賴關係。當一個對象的狀態發生改變時,所有依賴於它的對象都得到通知並被自動更新。 ...
  • 一篇文章帶你掌握MyBatis簡化框架——MyBatisPlus 我們在前面的文章中已經學習了目前開發所需的主流框架 類似於我們所學習的SpringBoot框架用於簡化Spring開發,我們的國人大大也開發了一款MyBatisPlus框架用來簡化MyBatis開發 下麵讓我們來逐步掌握MyBatis ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...