前言
目前開發(fā)的SpringBoot
項目在啟動的時候需要預(yù)加載一些資源斑粱。而如何實現(xiàn)啟動過程中執(zhí)行代碼龄恋,或啟動成功后執(zhí)行宴杀,是有很多種方式可以選擇贼急,我們可以在static代碼塊中實現(xiàn)患雏,也可以在構(gòu)造方法里實現(xiàn)鹏溯,也可以使用@PostConstruct
注解實現(xiàn)。
當然也可以去實現(xiàn)Spring的ApplicationRunner
與CommandLineRunner
接口去實現(xiàn)啟動后運行的功能淹仑。在這里整理一下丙挽,在這些位置執(zhí)行的區(qū)別以及加載順序肺孵。
java
自身的啟動時加載方式
static代碼塊
static靜態(tài)代碼塊,在類加載的時候即自動執(zhí)行颜阐。
構(gòu)造方法
在對象初始化時執(zhí)行平窘。執(zhí)行順序在static靜態(tài)代碼塊之后。
Spring啟動時加載方式
@PostConstruct
注解
PostConstruct
注解使用在方法上凳怨,這個方法在對象依賴注入初始化之后執(zhí)行瑰艘。
ApplicationRunner
和CommandLineRunner
SpringBoot
提供了兩個接口來實現(xiàn)Spring容器啟動完成后執(zhí)行的功能,兩個接口分別為CommandLineRunner
和ApplicationRunner
肤舞。
這兩個接口需要實現(xiàn)一個run方法紫新,將代碼在run中實現(xiàn)即可。這兩個接口功能基本一致李剖,其區(qū)別在于run方法的入?yún)ⅰ?code>ApplicationRunner的run方法入?yún)?code>ApplicationArguments芒率,為
CommandLineRunner
的run方法入?yún)镾tring數(shù)組。
何為ApplicationArguments
官方文檔解釋為:
Provides access to the arguments that were used to run a SpringApplication.
在Spring應(yīng)用運行時使用的訪問應(yīng)用參數(shù)篙顺。即我們可以獲取到
SpringApplication.run(…)
的應(yīng)用參數(shù)偶芍。
Order注解
當有多個類實現(xiàn)了
CommandLineRunner
和ApplicationRunner
接口時,可以通過在類上添加@Order注解來設(shè)定運行順序德玫。
代碼測試
為了測試啟動時運行的效果和順序匪蟀,編寫幾個測試代碼來運行看看。
TestPostConstruct
@Component
public class TestPostConstruct {
static {
System.out.println("static");
}
public TestPostConstruct() {
System.out.println("constructer");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}
TestApplicationRunner
@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("order1:TestApplicationRunner");
}
}
TestCommandLineRunner
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("order2:TestCommandLineRunner");
}
}
執(zhí)行結(jié)果
總結(jié)
Spring應(yīng)用啟動過程中化焕,肯定是要自動掃描有@Component
注解的類萄窜,加載類并初始化對象進行自動注入。加載類時首先要執(zhí)行static靜態(tài)代碼塊中的代碼撒桨,之后再初始化對象時會執(zhí)行構(gòu)造方法查刻。
在對象注入完成后,調(diào)用帶有@PostConstruct
注解的方法凤类。當容器啟動成功后穗泵,再根據(jù)@Order注解的順序調(diào)用CommandLineRunner
和ApplicationRunner
接口類中的run方法。
因此谜疤,加載順序為static
>constructer
>@PostConstruct
>CommandLineRunner
和ApplicationRunner
.