SpringBoot系列之啟動成功后執行業務的方法歸納

SpringBoot系列之啟動成功后執行業務邏輯。在Springboot項目中經常會遇到需要在項目啟動成功后,加一些業務邏輯的,比如緩存的預處理,配置參數的加載等等場景,下面給出一些常有的方法

實驗環境

  • JDK 1.8
  • SpringBoot 2.2.1
  • Maven 3.2+
  • Mysql 8.0.26
  • 開發工具
    • IntelliJ IDEA

    • smartGit

動手實踐

  • ApplicationRunner和CommandLineRunner

比較常有的使用Springboot框架提供的ApplicationRunnerCommandLineRunner,這兩種Runner可以實現在Springboot項目啟動后,執行我們自定義的業務邏輯,然后執行的順序可以通過@Order進行排序,參數值越小,越早執行

寫個測試類實現ApplicationRunner接口,注意加上@Component才能被Spring容器掃描到

package com.example.jedis.runner;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Order(1)
@Component
@Slf4j
public class TestApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {log.info("TestApplicationRunner");}
}

在這里插入圖片描述

實現CommandLineRunner接口

package com.example.jedis.runner;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;@Order(2)
@Component
@Slf4j
public class TestCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {log.info("TestCommandLineRunner");}
}

在這里插入圖片描述

  • ApplicationListener加ApplicationStartedEvent

SpringBoot基于Spring框架的事件監聽機制,提供ApplicationStartedEvent可以對SpringBoot啟動成功后的監聽,基于事件監聽機制,我們可以在SpringBoot啟動成功后做一些業務操作

package com.example.jedis.listener;import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.event.ApplicationStartedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;@Component
@Slf4j
public class TestApplicationListener implements ApplicationListener<ApplicationStartedEvent> {@Overridepublic void onApplicationEvent(ApplicationStartedEvent applicationStartedEvent) {log.info("onApplicationEvent");}
}

在這里插入圖片描述

  • SpringApplicationRunListener

如果要在啟動的其它階段做業務操作,可以實現SpringApplicationRunListener接口,例如要實現打印swagger的api接口文檔url,可以在對應方法進行拓展即可

package com.example.jedis.listener;import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;import java.net.InetAddress;@Slf4j
public class TestSpringApplicationRunListener implements SpringApplicationRunListener {private final SpringApplication application;private final String[] args;public TestSpringApplicationRunListener(SpringApplication application, String[] args) {this.application = application;this.args = args;}@Overridepublic void starting() {log.info("starting...");}@Overridepublic void environmentPrepared(ConfigurableEnvironment environment) {log.info("environmentPrepared...");}@Overridepublic void contextPrepared(ConfigurableApplicationContext context) {log.info("contextPrepared...");}@Overridepublic void contextLoaded(ConfigurableApplicationContext context) {log.info("contextLoaded...");}@Overridepublic void started(ConfigurableApplicationContext context) {log.info("started...");}@SneakyThrows@Overridepublic void running(ConfigurableApplicationContext context) {log.info("running...");ConfigurableEnvironment environment = context.getEnvironment();String port = environment.getProperty("server.port");String contextPath = environment.getProperty("server.servlet.context-path");String docPath = port + "" + contextPath + "/doc.html";String externalAPI = InetAddress.getLocalHost().getHostAddress();log.info("\n Swagger API: "+ "Local-API: \t\thttp://127.0.0.1:{}\n\t"+ "External-API: \thttp://{}:{}\n\t",docPath, externalAPI, docPath);}@Overridepublic void failed(ConfigurableApplicationContext context, Throwable exception) {log.info("failed...");}
}

在/META-INF/spring.factories配置文件配置:

org.springframework.boot.SpringApplicationRunListener=\com.example.jedis.listener.TestSpringApplicationRunListener

在這里插入圖片描述

源碼分析

在Springboot的run方法里找到如下的源碼,大概看一下就可以知道里面是封裝了對RunnerSpringApplicationRunListener的調用

public ConfigurableApplicationContext run(String... args) {StopWatch stopWatch = new StopWatch();stopWatch.start();ConfigurableApplicationContext context = null;Collection<SpringBootExceptionReporter> exceptionReporters = new ArrayList();this.configureHeadlessProperty();SpringApplicationRunListeners listeners = this.getRunListeners(args);// SpringApplicationRunListener調用listeners.starting();Collection exceptionReporters;try {ApplicationArguments applicationArguments = new DefaultApplicationArguments(args);ConfigurableEnvironment environment = this.prepareEnvironment(listeners, applicationArguments);this.configureIgnoreBeanInfo(environment);Banner printedBanner = this.printBanner(environment);context = this.createApplicationContext();exceptionReporters = this.getSpringFactoriesInstances(SpringBootExceptionReporter.class, new Class[]{ConfigurableApplicationContext.class}, context);this.prepareContext(context, environment, listeners, applicationArguments, printedBanner);this.refreshContext(context);this.afterRefresh(context, applicationArguments);stopWatch.stop();if (this.logStartupInfo) {(new StartupInfoLogger(this.mainApplicationClass)).logStarted(this.getApplicationLog(), stopWatch);}// SpringApplicationRunListener startlisteners.started(context);// 調用所有的Runnerthis.callRunners(context, applicationArguments);} catch (Throwable var10) {this.handleRunFailure(context, var10, exceptionReporters, listeners);throw new IllegalStateException(var10);}try {// SpringApplicationRunListener running執行listeners.running(context);return context;} catch (Throwable var9) {this.handleRunFailure(context, var9, exceptionReporters, (SpringApplicationRunListeners)null);throw new IllegalStateException(var9);}}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/209961.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/209961.shtml
英文地址,請注明出處:http://en.pswp.cn/news/209961.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

python dataframe 列中 字符串( ‘2815512706605‘)過大 轉不了float 用Decimal

from decimal import Decimaldf["accFillSz"] df["accFillSz"].apply(lambda x: Decimal(x)) 2815512706605這個值超出了Python中float類型的最大表示范圍,無法直接轉換為浮點數。 Python中float類型使用IEEE 754標準的64位雙精度浮點數表示,最大值大約為…

歐拉回路歐拉路【詳解】

1.引入 2.概念 3.解決方法 4.例題 5.回顧 1.引入 經典的七橋問題 哥尼斯堡是位于普累格河上的一座城市&#xff0c;它包含兩個島嶼及連接它們的七座橋&#xff0c;如下圖所示。 可否走過這樣的七座橋&#xff0c;而且每橋只走過一次&#xff1f; 你怎樣證明&#xff1f;…

【Linux top命令】

文章目錄 深入了解Linux top命令&#xff1a;實時監控系統性能1. 什么是top命令&#xff1f;2. 使用top命令3. top命令交互操作 深入了解Linux top命令&#xff1a;實時監控系統性能 1. 什么是top命令&#xff1f; top命令是一個用于實時監控系統性能的文本界面工具。它顯示當…

Linux上使用獨立顯卡Tesla T4(測試視頻壓縮)

背景 將視頻處理程序單獨部署至K8S之外&#xff0c;使用獨立GPU顯卡的一臺服務器上。 需事先對GPU性能做簡單測試。 已通過zabbix對Linux進行了系統資源監控。 已通過PrometheusGrafana對顯卡Tesla T4做了性能監控。 逐步補充&#xff0c;稍等 2023年12月6日 操作 查看當前…

鴻蒙Harmony開發初探

一、背景 9月25日華為秋季全場景新品發布會&#xff0c;余承東宣布鴻蒙HarmonyOS NEXT蓄勢待發&#xff0c;不再支持安卓應用。網易有道、同程旅行、美團、國航、阿里等公司先后宣布啟動鴻蒙原生應用開發工作。 二、鴻蒙Next介紹 HarmonyOS是一款面向萬物互聯&#xff0c;全…

[Linux] 基于LAMP架構安裝論壇

一、安裝Discuz論壇 1.1 創建數據庫&#xff0c;并進行授權 mysql -u root -p123CREATE DATABASE bbs; #創建一個數據庫GRANT all ON bbs.* TO bbsuser% IDENTIFIED BY admin123; #把bbs數據庫里面所有表的權限授予給bbsuser,并設置密碼admin123flush privileges; #刷新數據庫…

Java 中的抽象類與接口:深入理解與應用

文章目錄 什么是抽象類&#xff1f;什么是接口&#xff1f;抽象類和接口的使用場景抽象類和接口的區別結論 在 Java 編程語言中&#xff0c;抽象類和接口是兩種重要的機制&#xff0c;用于實現抽象化和多態性。這兩種機制都允許我們定義一種通用的類型&#xff0c;然后通過繼承…

數據結構——棧與棧排序

棧的特性 棧是一種遵循后進先出&#xff08;LIFO&#xff09;原則的數據結構。其基本操作包括&#xff1a; push&#xff1a;將元素添加到棧頂。pop&#xff1a;移除棧頂元素。peek&#xff1a;查看棧頂元素&#xff0c;但不移除。 棧排序的原理 棧排序的核心是使用兩個棧&…

[滲透測試學習] Devvortex - HackTheBox

文章目錄 信息搜集解題步驟提交flag 信息搜集 掃描端口 nmap -sV -sC -p- -v --min-rate 1000 10.10.11.242發現80端口有http服務&#xff0c;并且是nginx服務 嘗試訪問web界面&#xff0c;發現跳轉到http://devvortex.htb/無法訪問 我們用vim添加該域名即可 sudo vim /etc/…

J.408之數據結構

J-408之數據結構_北京信息科技大學第十五屆程序設計競賽&#xff08;同步賽&#xff09; (nowcoder.com) 思維好題&#xff0c;直接用兩個set存沒出現的數字就好了 // Problem: 408之數據結構 // Contest: NowCoder // URL: https://ac.nowcoder.com/acm/contest/68572/J // Me…

ClickHouse安裝和部署

ClickHouse安裝過程&#xff1a; ClickHouse支持運行在主流64位CPU架構&#xff08;X86、AArch和PowerPC&#xff09;的Linux操作 系統之上&#xff0c;可以通過源碼編譯、預編譯壓縮包、Docker鏡像和RPM等多種方法進行安裝。由于篇幅有限&#xff0c;本節著重講解離線RPM的安…

RAW和YUV的區別

RAW是指未經過任何壓縮或處理的原始圖像數據。在攝像頭中&#xff0c;原始圖像數據可以是來自圖像傳感器的未經處理的像素值。這些原始數據通常以一種Bayer模式的形式存在&#xff0c;其中每個像素僅包含一種顏色信息&#xff08;紅色、綠色或藍色&#xff09;&#xff0c;需要…

【開源】基于Vue和SpringBoot的在線課程教學系統

項目編號&#xff1a; S 014 &#xff0c;文末獲取源碼。 \color{red}{項目編號&#xff1a;S014&#xff0c;文末獲取源碼。} 項目編號&#xff1a;S014&#xff0c;文末獲取源碼。 目錄 一、摘要1.1 系統介紹1.2 項目錄屏 二、研究內容2.1 課程類型管理模塊2.2 課程管理模塊2…

Redis Bitmaps 數據結構模型位操作

Bitmaps 數據結構模型 Bitmap 本身不是一種數據結構&#xff0c;實際上它就是字符串&#xff0c;但是它可以對字符串的位進行操作。 比如 “abc” 對應的 ASCII 碼分別是 97、98、99。對應的二進制分別是 01100010、01100010、01100011, 如下所示&#xff1a; a b …

HTML5+CSS3+JS小實例:文字依次點擊驗證

實例:文字依次點擊驗證 技術棧:HTML+CSS+JS 效果: 源碼: 【HTML】 <!DOCTYPE html> <html><head><meta http-equiv="content-type" content="text/html; charset=utf-8"><meta name="viewport" content=&quo…

十七、FreeRTOS之FreeRTOS事件標志組

本節需要掌握以下內容&#xff1a; 1&#xff0c;事件標志組簡介&#xff08;了解&#xff09; 2&#xff0c;事件標志組相關API函數介紹&#xff08;熟悉&#xff09; 3&#xff0c;事件標志組實驗&#xff08;掌握&#xff09; 4&#xff0c;課堂總結&#xff08;掌握&am…

04_W5500_TCP_Server

上一節我們完成了TCP_Client實驗&#xff0c;這節使用W5500作為服務端與TCP客戶端進行通信。 目錄 1.W5500服務端要做的&#xff1a; 2.代碼分析&#xff1a; 3.測試&#xff1a; 1.W5500服務端要做的&#xff1a; 服務端只需要打開socket&#xff0c;然后監聽端口即可。 2…

基于Spring Boot的水產養殖管理系統

文章目錄 項目介紹主要功能截圖:部分代碼展示設計總結項目獲取方式?? 作者主頁:超級無敵暴龍戰士塔塔開 ?? 簡介:Java領域優質創作者??、 簡歷模板、學習資料、面試題庫【關注我,都給你】 ??文末獲取源碼聯系?? 項目介紹 基于Spring Boot的水產養殖管理系統,jav…

HarmonyOS Developer——鴻蒙【構建第一個JS應用(FA模型)】

創建JS工程 JS工程目錄結構 構建第一個頁面 構建第二個頁面 實現頁面間的跳轉 使用真機運行應用 說明 為確保運行效果&#xff0c;本文以使用DevEco Studio 3.1 Release版本為例&#xff0c;點擊此處獲取下載鏈接。 創建JS工程 若首次打開DevEco Studio&#xff0c;請點擊…

蝦皮什么商品好賣

在蝦皮&#xff08;Shopee&#xff09;平臺上&#xff0c;有許多商品類別都表現出了較好的銷售情況。然而&#xff0c;隨著時間和地區的變化&#xff0c;熱銷商品也會有所不同。本文將介紹一些在蝦皮平臺上表現較好的商品類別&#xff0c;并提供一些建議&#xff0c;幫助您在蝦…