當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
SpringBoot使用CommandLineRunner和ApplicationRunner项目初始化事件
生活随笔
收集整理的這篇文章主要介紹了
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项目初始化事件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java进阶:BlockingQueue
- 下一篇: SpringBoot @PostCons