我們在項目中會用到項目啟動任務(wù),即項目在啟動的時候需要做的一些事,例如:數(shù)據(jù)初始化、獲取第三方數(shù)據(jù)等等,那么如何在SpringBoot 中實現(xiàn)啟動任務(wù),一起來看看吧
SpringBoot 中提供了兩種項目啟動方案,CommandLineRunner 和 ApplicationRunner
一、CommandLineRunner
使用 CommandLineRunner ,需要自定義一個類區(qū)實現(xiàn) CommandLineRunner 接口,例如:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 項目啟動任務(wù)類 */ @Component @Order ( 100 ) public class StartTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { } } |
我們首先使用 @Component 將該類注冊成為 Spring 容器中的一個 Bean
然后使用 @Order(100) 標(biāo)明該啟動任務(wù)的優(yōu)先級,值越大,表示優(yōu)先級越小
實現(xiàn) CommandLineRunner 接口,并重寫 run() 方法,當(dāng)項目啟動時,run() 方法會被執(zhí)行,run() 方法中的參數(shù)有兩種傳遞方式
1、在 IDEA 中傳入?yún)?shù)
2、將項目打包,在啟動項目時,輸入以下命令:
1
|
java -jar demo- 0.0 . 1 -SNAPSHOT.jar hello world |
二、ApplicationRunner
ApplicationRunner 與 CommandLineRunner 的用法基本一致,只是接收的參數(shù)不一樣,可以接收 key-value 形式的參數(shù),如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 項目啟動任務(wù)類 */ @Component @Order ( 100 ) public class StartTask implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { } } |
關(guān)于 run 方法的參數(shù) ApplicationArguments:
1、args.getNonOptionArgs();可以用來獲取命令行中的無key參數(shù)(和CommandLineRunner一樣)
2、args.getOptionNames();可以用來獲取所有key/value形式的參數(shù)的key
3、args.getOptionValues(key));可以根據(jù)key獲取key/value 形式的參數(shù)的value
4、args.getSourceArgs(); 則表示獲取命令行中的所有參數(shù)
傳參方式:
1、在 IDEA 中傳入?yún)?shù)
2、將項目打包,在啟動項目時,輸入以下命令:
1
|
java -jar demo- 0.0 . 1 -SNAPSHOT.jar hello world --name=xiaoming |
以上就是在 SpringBoot 中實現(xiàn)項目啟動任務(wù)的兩種方式,用法基本一致,主要體現(xiàn)在傳參的不同上
到此這篇關(guān)于SpringBoot中實現(xiàn)啟動任務(wù)的實現(xiàn)步驟的文章就介紹到這了,更多相關(guān)SpringBoot 啟動任務(wù)內(nèi)容請搜索服務(wù)器之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持服務(wù)器之家!
原文鏈接:https://blog.csdn.net/qq_40065776/article/details/106751864