SpringBoot 啟動時自動執(zhí)行代碼的幾種方式,還有誰不會??
往期熱門文章:
3、遭棄用的 Docker Desktop 放大招!宣布支持 Linux
來源:blog.csdn.net/u011291072/article/details/81813662
前言
java自身的啟動時加載方式
Spring啟動時加載方式
代碼測試
總結(jié)
前言
@PostConstruct注解實現(xiàn)。ApplicationRunner與CommandLineRunner接口去實現(xiàn)啟動后運行的功能。在這里整理一下,在這些位置執(zhí)行的區(qū)別以及加載順序。java自身的啟動時加載方式
static代碼塊
構造方法
Spring啟動時加載方式
@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(…)的應用參數(shù)。Order注解
CommandLineRunner和ApplicationRunner接口時,可以通過在類上添加@Order注解來設定運行順序。代碼測試
@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注解的類,加載類并初始化對象進行自動注入。加載類時首先要執(zhí)行static靜態(tài)代碼塊中的代碼,之后再初始化對象時會執(zhí)行構造方法。@PostConstruct注解的方法。當容器啟動成功后,再根據(jù)@Order注解的順序調(diào)用CommandLineRunner和ApplicationRunner接口類中的run方法。static>constructer>@PostConstruct>CommandLineRunner和ApplicationRunner.
最近熱文閱讀:
1、如何寫出讓同事吐血的代碼? 2、遭棄用的 Docker Desktop 放大招!宣布支持 Linux 3、IDEA公司再發(fā)新神器!超越 VS Code 騷操作! 4、推薦好用 Spring Boot 內(nèi)置工具類 5、五個刁鉆的String面試問題及解答 6、IntelliJ平臺將完全停止使用Log4j 7、神操作!我把 3000 行代碼重構成 15 行! 8、我用Java幾分鐘處理完30億個數(shù)據(jù)... 9、一款自動生成單元測試的 IDEA 插件 10、微軟 10 大最受歡迎 GitHub 項目,最高 Star 數(shù)量 13 萬 關注公眾號,你想要的Java都在這
評論
圖片
表情
