SpringBoot中實現啟動任務的實現步驟
我們在專案中會用到專案啟動任務,即專案在啟動的時候需要做的一些事,例如:資料初始化、獲取第三方資料等等,那麼如何在SpringBoot 中實現啟動任務,一起來看看吧
SpringBoot 中提供了兩種專案啟動方案,CommandLineRunner 和 ApplicationRunner
一、CommandLineRunner
使用 CommandLineRunner ,需要自定義一個類區實現 CommandLineRunner 介面,例如:
import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 專案啟動任務類 */ @Component @Order(100) public class StartTask implements CommandLineRunner { @Override public void run(String... args) throws Exception { } }
我們首先使用 @Component 將該類註冊成為 Spring 容器中的一個 Bean
然後使用 @Order(100) 標明該啟動任務的優先順序,值越大,表示優先順序越小
實現 CommandLineRunner 介面,並重寫 run() 方法,當專案啟動時,run() 方法會被執行,run() 方法中的引數有兩種傳遞方式
1、在 IDEA 中傳入引數
2、將專案打包,在啟動專案時,輸入以下命令:
java -jar demo-0.0.1-SNAPSHOT.jar hello world
二、ApplicationRunner
ApplicationRunner 與 CommandLineRunner 的用法基本一致,只是接收的引數不一樣,可以接收 key-value 形式的引數,如下:
import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 專案啟動任務類 */ @Component @Order(100) public class StartTask implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { } }
關於 run 方法的引數 ApplicationArguments:
1、args.getNonOptionArgs();可以用來獲取命令列中的無key引數(和CommandLineRunner一樣)
2、args.getOptionNames();可以用來獲取所有key/value形式的引數的key
3、args.getOptionValues(key));可以根據key獲取key/value 形式的引數的value
4、args.getSourceArgs(); 則表示獲取命令列中的所有引數
傳參方式:
1、在 IDEA 中傳入引數
2、將專案打包,在啟動專案時,輸入以下命令:
java -jar demo-0.0.1-SNAPSHOT.jar hello world --name=xiaoming
以上就是在 SpringBoot 中實現專案啟動任務的兩種方式,用法基本一致,主要體現在傳參的不同上
到此這篇關於SpringBoot中實現啟動任務的實現步驟的文章就介紹到這了,更多相關SpringBoot 啟動任務內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!