SpringBoot 在啟動時執行程式碼
阿新 • • 發佈:2019-01-27
在Spring boot專案的實際開發中,我們有時需要專案服務啟動時載入一些資料或預先完成某些動作。為了解決這樣的問題,Spring boot 為我們提供了一個方法:通過實現介面 CommandLineRunner 來實現這樣的需求。
實現方式:只需要一個類即可,無需其他配置。
實現步驟:
1.建立實現介面 CommandLineRunner 的類 MyStartupRunnerTest
- package com.energy;
- import org.springframework.boot.CommandLineRunner;
-
import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- /**
- * Created by CavanLiu on 2017/2/28 0028.
- */
- @Component
- @Order(value=1)
- publicclass MyStartupRunnerTest implements CommandLineRunner
- {
- @Override
- publicvoid run(String... args) throws Exception
- {
-
System.out.println(">>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<"
- }
- }
2.建立實現介面CommandLineRunner 的類 MyStartupRunnerTest2
- package com.energy;
- import org.springframework.boot.CommandLineRunner;
- import org.springframework.core.annotation.Order;
- import org.springframework.stereotype.Component;
- /**
- * Created by CavanLiu on 2017/2/28 0028.
- */
-
@Component
- @Order(value=2)
- publicclass MyStartupRunnerTest2 implements CommandLineRunner
- {
- @Override
- publicvoid run(String... args) throws Exception
- {
- System.out.println(">>>>This is MyStartupRunnerTest Order=2. Only testing CommandLineRunner...<<<<");
- }
- }
3.啟動Spring boot後檢視控制檯輸出資訊,如下所示:
- >>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<
- >>>>This is MyStartupRunnerTest2 Order=2. Only testing CommandLineRunner...<<<<
4.Application啟動類程式碼略。
說明:CommandLineRunner介面的執行順序是依據@Order註解的value由小到大執行,即value值越小優先順序越高。