1. 程式人生 > >SpringBoot 在啟動時執行程式碼

SpringBoot 在啟動時執行程式碼

在Spring boot專案的實際開發中,我們有時需要專案服務啟動時載入一些資料或預先完成某些動作。為了解決這樣的問題,Spring boot 為我們提供了一個方法:通過實現介面 CommandLineRunner 來實現這樣的需求。

實現方式:只需要一個類即可,無需其他配置。 

實現步驟:

1.建立實現介面 CommandLineRunner 的類 MyStartupRunnerTest

  1. package com.energy;  
  2. import org.springframework.boot.CommandLineRunner;  
  3. import org.springframework.core.annotation.Order;  
  4. import org.springframework.stereotype.Component;  
  5. /** 
  6.  * Created by CavanLiu on 2017/2/28 0028. 
  7.  */
  8. @Component
  9. @Order(value=1)
  10. publicclass MyStartupRunnerTest implements CommandLineRunner  
  11. {  
  12.     @Override
  13.     publicvoid run(String... args) throws Exception  
  14.     {  
  15.         System.out.println(">>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<"
    );  
  16.     }  
  17. }  

2.建立實現介面CommandLineRunner 的類 MyStartupRunnerTest2

  1. package com.energy;  
  2. import org.springframework.boot.CommandLineRunner;  
  3. import org.springframework.core.annotation.Order;  
  4. import org.springframework.stereotype.Component;  
  5. /** 
  6.  * Created by CavanLiu on 2017/2/28 0028. 
  7.  */
  8. @Component
  9. @Order(value=2)
  10. publicclass MyStartupRunnerTest2 implements CommandLineRunner  
  11. {  
  12.     @Override
  13.     publicvoid run(String... args) throws Exception  
  14.     {  
  15.         System.out.println(">>>>This is MyStartupRunnerTest Order=2. Only testing CommandLineRunner...<<<<");  
  16.     }  
  17. }  

3.啟動Spring boot後檢視控制檯輸出資訊,如下所示:

  1. >>>>This is MyStartupRunnerTest Order=1. Only testing CommandLineRunner...<<<<  
  2. >>>>This is MyStartupRunnerTest2 Order=2. Only testing CommandLineRunner...<<<<  

4.Application啟動類程式碼略。

說明:CommandLineRunner介面的執行順序是依據@Order註解的value由小到大執行,即value值越小優先順序越高。