日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > javascript >内容正文

javascript

SpringBoot使用CommandLineRunner和ApplicationRunner项目初始化事件

發布時間:2025/3/19 javascript 23 豆豆
生活随笔 收集整理的這篇文章主要介紹了 SpringBoot使用CommandLineRunner和ApplicationRunner项目初始化事件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1. 概述

在實際開發工作中,有時需要在項目啟動的時候初始化資源,例如:緩存、定時任務等等。

Spring Boot 提供了這樣的方案,只要創建 Bean 實現CommandLineRunner或者ApplicationRunner即可。這兩個的作用是相同的,只是提供的參數略有不同。

如果存在多個類實現CommandLineRunner或者ApplicationRunner,可以添加 @Order 注解或者實現 Ordered 接口來控制執行順序。

2. Demo

先創建一個空的 Spring Boot 項目,創建過程就不演示了。

2.1 CommandLineRunner

MyCommandLineRunner實現類,輸出args參數

@Component public class MyCommandLineRunner implements CommandLineRunner {@Overridepublic void run(String... args) throws Exception {String argsStr = String.join(",", args);System.out.println("===================================================================");System.out.println();System.out.println("CommandLineRunner:" + argsStr);} }

應用程序啟動類:

@SpringBootApplication public class ApplicationRunnerApplication {public static void main(String[] args) {SpringApplication.run(ApplicationRunnerApplication.class, args);System.out.println("SpringApplication.run 執行完畢");}}

配置Idea的啟動參數


在這里輸入“a1 a2 a3”,然后OK保存


最后啟動運行程序,輸出結果如下:

2.2 ApplicationRunner

創建MyApplicationRunner 類,代碼:

@Component public class MyApplicationRunner implements ApplicationRunner {@Overridepublic void run(ApplicationArguments args) throws Exception {String argsStr = String.join(",", args.getSourceArgs());System.out.println("ApplicationRunner:" + argsStr);} }

直接運行

總結

以上是生活随笔為你收集整理的SpringBoot使用CommandLineRunner和ApplicationRunner项目初始化事件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。