Spring Boot 初始化運行特定方法解析
Spring Boot提供了兩種 “開機自啟動” 的方式,ApplicationRunner和CommandLineRunner
這兩種方式的目的是為了滿足,在容器啟動時like執(zhí)行某些方法。我們可以通過實現(xiàn)ApplicationRunner或者CommandLineRunner來實現(xiàn),他們都是在SpringAppliaction執(zhí)行之后開始執(zhí)行的。這個特性可以讓我們自定義一些在容器啟動時需要初始化的邏輯
ApplicationRunner接口:
官方doc:
Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple ApplicationRunner beans can be defined within the same application context and can be ordered using the Ordered
當該接口包含在SpringApplication中時執(zhí)行。多個ApplicationRunner通過Order直接進行排序:
/**
* 初始化類
*/
@Order(1) // @Order注解可以改變執(zhí)行順序,越小越先執(zhí)行
@Component
public class MyApplicationRunner1 implements ApplicationRunner {
/**
* 會在服務啟動完成后立即執(zhí)行
*/
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("MyApplicationRunner1----" + arg0);
}
}
/**
* 初始化類
*/
@Order(2)
@Component
public class MyApplicationRunner2 implements ApplicationRunner {
/**
* 會在服務啟動完成后立即執(zhí)行
*/
@Override
public void run(ApplicationArguments arg0) throws Exception {
System.out.println("MyApplicationRunner2----" + arg0);
}
}
容器啟動后的運行結果:

可以看到多個ApplicationRunner執(zhí)行順序是按照Order中的值執(zhí)行的,并且每個的入?yún)⒍际峭粋€ApplicationArguments實例(具體原因后面分析)
CommandLineRunner接口:
二者的官方doc基本一樣,區(qū)別在于接收的參數(shù)不一樣
/**
* 初始化類
*/
@Order(1) // @Order注解可以改變執(zhí)行順序,越小越先執(zhí)行
@Component
public class MyCommandLineRunner1 implements CommandLineRunner {
/**
* 會在服務啟動完成后立即執(zhí)行
*/
@Override
public void run(String... args) throws Exception {
System.out.println("MyCommandLineRunner1----" + args);
}
}
/**
* 初始化類
*/
@Order(2)
@Component
public class MyCommandLineRunner2 implements CommandLineRunner {
/**
* 會在服務啟動完成后立即執(zhí)行
*/
@Override
public void run(String... args) throws Exception {
System.out.println("MyCommandLineRunner2----" + args);
}
}
容器啟動后的運行結果:

可以看到多個CommandLineRunner的執(zhí)行效果跟ApplicationRunner一模一樣
最后看下源碼:
SpringApplication啟動時,會執(zhí)行其run方法中的afterRefresh方法:

在afterRefresh中可以看到這兩個接口被執(zhí)行,并且每個ApplicationRunner或CommandLineRunner實例都是用的同一個入?yún)ⅲ?/p>

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java 高并發(fā)十: JDK8對并發(fā)的新支持詳解
本文主要介紹Java 高并發(fā)JDK8的支持,這里整理了詳細的資料及1. LongAdder 2. CompletableFuture 3. StampedLock的介紹,有興趣的小伙伴可以參考下2016-09-09
Redisson分布式閉鎖RCountDownLatch的使用詳細講解
分布式鎖和我們java基礎中學習到的synchronized略有不同,synchronized中我們的鎖是個對象,當前系統(tǒng)部署在不同的服務實例上,單純使用synchronized或者lock已經(jīng)無法滿足對庫存一致性的判斷。本次主要講解基于rediss實現(xiàn)的分布式鎖2023-02-02
netty?pipeline中的inbound和outbound事件傳播分析
這篇文章主要為大家介紹了netty?pipeline中的inbound和outbound事件傳播分析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-04-04
Mybatis 動態(tài)SQL的幾種實現(xiàn)方法
這篇文章主要介紹了Mybatis 動態(tài)SQL的幾種實現(xiàn)方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-11-11

