新聞中心
SpringBoot 啟動時(shí)實(shí)現(xiàn)自動執(zhí)行代碼的幾種方式
- 前言
- java自身的啟動時(shí)加載方式
- Spring啟動時(shí)加載方式
- 代碼測試
- 總結(jié)
前言
當(dāng)然也可以去實(shí)現(xiàn)Spring的ApplicationRunner與CommandLineRunner接口去實(shí)現(xiàn)啟動后運(yùn)行的功能。在這里整理一下,在這些位置執(zhí)行的區(qū)別以及加載順序。

在泰山等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供網(wǎng)站設(shè)計(jì)、網(wǎng)站建設(shè) 網(wǎng)站設(shè)計(jì)制作按需網(wǎng)站策劃,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),高端網(wǎng)站設(shè)計(jì),營銷型網(wǎng)站,成都外貿(mào)網(wǎng)站建設(shè)公司,泰山網(wǎng)站建設(shè)費(fèi)用合理。
java自身的啟動時(shí)加載方式
static代碼塊
static靜態(tài)代碼塊,在類加載的時(shí)候即自動執(zhí)行。
構(gòu)造方法
在對象初始化時(shí)執(zhí)行。執(zhí)行順序在static靜態(tài)代碼塊之后。
Spring啟動時(shí)加載方式
@PostConstruct注解
PostConstruct注解使用在方法上,這個(gè)方法在對象依賴注入初始化之后執(zhí)行。
ApplicationRunner和CommandLineRunner
SpringBoot提供了兩個(gè)接口來實(shí)現(xiàn)Spring容器啟動完成后執(zhí)行的功能,兩個(gè)接口分別為CommandLineRunner和ApplicationRunner。
這兩個(gè)接口需要實(shí)現(xiàn)一個(gè)run方法,將代碼在run中實(shí)現(xiàn)即可。這兩個(gè)接口功能基本一致,其區(qū)別在于run方法的入?yún)ⅰpplicationRunner的run方法入?yún)锳pplicationArguments,為CommandLineRunner的run方法入?yún)镾tring數(shù)組。
何為ApplicationArguments
官方文檔解釋為:
”Provides access to the arguments that were used to run a SpringApplication.
在Spring應(yīng)用運(yùn)行時(shí)使用的訪問應(yīng)用參數(shù)。即我們可以獲取到SpringApplication.run(…)的應(yīng)用參數(shù)。
Order注解
當(dāng)有多個(gè)類實(shí)現(xiàn)了CommandLineRunner和ApplicationRunner接口時(shí),可以通過在類上添加@Order注解來設(shè)定運(yùn)行順序。
代碼測試
為了測試啟動時(shí)運(yùn)行的效果和順序,編寫幾個(gè)測試代碼來運(yùn)行看看。
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注解的類,加載類并初始化對象進(jìn)行自動注入。加載類時(shí)首先要執(zhí)行static靜態(tài)代碼塊中的代碼,之后再初始化對象時(shí)會執(zhí)行構(gòu)造方法。
在對象注入完成后,調(diào)用帶有@PostConstruct注解的方法。當(dāng)容器啟動成功后,再根據(jù)@Order注解的順序調(diào)用CommandLineRunner和ApplicationRunner接口類中的run方法。
因此,加載順序?yàn)閟tatic>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.
網(wǎng)站名稱:SpringBoot 啟動時(shí)實(shí)現(xiàn)自動執(zhí)行代碼的幾種方式
文章URL:http://fisionsoft.com.cn/article/cccehho.html


咨詢
建站咨詢
