SpringBoot(十四):CommandLineRunner-初始化資源
阿新 • • 發佈:2018-11-06
版權宣告
- 本文作者:低調小熊貓
本文連結:https://aodeng.cc/archives/springbootshi-si- 版權宣告:本文采用知識共享署名 4.0 國際許可協議進行許可。轉載請註明出處!
- 參考:純潔的微笑:Spring Boot 如何解決專案啟動時初始化資源
單純的廣告
個人部落格:https://aodeng.cc
微信公眾號:低調小熊貓
QQ群:756796932
簡介
CommandLineRunner介面的Component會在spring bean初始化之後,SpringApplication run之前執行,可以控制在專案啟動前初始化資原始檔,比如初始化執行緒池,提前載入好加密證書等
實現介面(CommandLineRunner)
@order表示載入順序,-1,1,2,按照最小先執行的規則
Run類
@Component
@Order(-1)
public class Run implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Run");
}
}
我們多建立幾個類實現介面
Run2類
@Component public class Run2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("Run2"); } }
Run3類
@Component
@Order(1)
public class Run3 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("Run3");
}
}
啟動程式
@SpringBootApplication public class Application { public static void main(String[] args) { System.out.println("----------start--------"); SpringApplication.run(Application.class,args); System.out.println("----------end--------"); } }
執行效果
(輸出在start和end之間,說明CommandLineRunner 的執行時機,是在所有 Spring Beans 都初始化之後,SpringApplication.run() 之前執行,Run,Run3,Run2執行的順序也是我們@order註解的順序了)
----------start--------
Run
Run3
Run2
----------end--------
就是學習習慣做筆記了,這樣印象深刻點,不論你在哪裡看到我的文章,對你有幫助就好。下面是我放在
Github的原始碼:https://github.com/java-aodeng/hope