Spring Boot 啟動(dòng)時(shí)自動(dòng)執(zhí)行代碼的幾種方式,還有誰(shuí)不會(huì)??
往期熱門文章:
1、面試官 | Spring Boot 項(xiàng)目如何統(tǒng)一結(jié)果,統(tǒng)一異常,統(tǒng)一日志?
來(lái)源:blog.csdn.net/u011291072/article/details/81813662
前言
java自身的啟動(dòng)時(shí)加載方式
Spring啟動(dòng)時(shí)加載方式
代碼測(cè)試
總結(jié)
前言
@PostConstruct注解實(shí)現(xiàn)。ApplicationRunner與CommandLineRunner接口去實(shí)現(xiàn)啟動(dòng)后運(yùn)行的功能。在這里整理一下,在這些位置執(zhí)行的區(qū)別以及加載順序。java自身的啟動(dòng)時(shí)加載方式
static代碼塊
構(gòu)造方法
Spring啟動(dòng)時(shí)加載方式
@PostConstruct注解
ApplicationRunner和CommandLineRunner
CommandLineRunner和ApplicationRunner。ApplicationRunner的run方法入?yún)?/span>ApplicationArguments,為CommandLineRunner的run方法入?yún)镾tring數(shù)組。何為ApplicationArguments
Provides access to the arguments that were used to run a SpringApplication.
SpringApplication.run(…)的應(yīng)用參數(shù)。Order注解
CommandLineRunner和ApplicationRunner接口時(shí),可以通過在類上添加@Order注解來(lái)設(shè)定運(yùn)行順序。代碼測(cè)試
@Component
public class TestPostConstruct {
static {
System.out.println("static");
}
public TestPostConstruct() {
System.out.println("constructer");
}
@PostConstruct
public void init() {
System.out.println("PostConstruct");
}
}
@Component
@Order(1)
public class TestApplicationRunner implements ApplicationRunner{
@Override
public void run(ApplicationArguments applicationArguments) throws Exception {
System.out.println("order1:TestApplicationRunner");
}
}
@Component
@Order(2)
public class TestCommandLineRunner implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println("order2:TestCommandLineRunner");
}
}
總結(jié)
@Component注解的類,加載類并初始化對(duì)象進(jìn)行自動(dòng)注入。加載類時(shí)首先要執(zhí)行static靜態(tài)代碼塊中的代碼,之后再初始化對(duì)象時(shí)會(huì)執(zhí)行構(gòu)造方法。@PostConstruct注解的方法。當(dāng)容器啟動(dòng)成功后,再根據(jù)@Order注解的順序調(diào)用CommandLineRunner和ApplicationRunner接口類中的run方法。static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.
最近熱文閱讀:
1、面試官 | Spring Boot 項(xiàng)目如何統(tǒng)一結(jié)果,統(tǒng)一異常,統(tǒng)一日志? 2、為什么不建議使用ON DUPLICATE KEY UPDATE? 3、Java8 Stream,過分絲滑! 4、8 種最坑SQL語(yǔ)法,工作中踩過嗎? 5、Java 語(yǔ)言“坑爹” TOP 10 6、你還不明白如何解決分布式Session?看這篇就夠了! 7、能解決 80% 故障的排查思路 8、程序員坐牢了,會(huì)被安排寫代碼嗎? 9、面試被問Nginx,怎么破? 10、為什么很多 SpringBoot 開發(fā)者放棄了 Tomcat,選擇了 Undertow? 關(guān)注公眾號(hào),你想要的Java都在這里
評(píng)論
圖片
表情
