SpringBoot(十四):CommandLineRunner-初始化資源
個人部落格:https://aodeng.cc
微信公眾號:低調小熊貓
QQ群:756796932
簡介
CommandLineRunner介面的Component會在spring bean初始化之後,SpringApplication run之前執行,可以控制在專案啟動前初始化資原始檔,比如初始化執行緒池,提前載入好加密證書等
實現介面(CommandLineRunner)
ofollow,noindex" target="_blank">@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--------
就是學習習慣做筆記了,這樣印象深刻點,不論你在哪裡看到我的文章,對你有幫助就好。下面是我放在