Spring Boot 項目啟動自動執(zhí)行方法的兩種實現(xiàn)方式
實際應(yīng)用場景:
springboot項目啟動成功后執(zhí)行一段代碼,如系統(tǒng)常量,配置、代碼集等等初始化操作;執(zhí)行多個方法時,執(zhí)行順序使用Order注解或Order接口來控制。
Springboot給我們提供了兩種方式
第一種實現(xiàn)ApplicationRunner接口
package org.mundo.demo.core; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(2) public class ApplicationRunnerImpl implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("通過實現(xiàn)ApplicationRunner接口,在spring boot項目啟動后執(zhí)行代碼..."); } }
第二種實現(xiàn)CommandLineRunner接口
package org.mundo.demo.core; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(1) public class CommandLineRunnerImpl implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("通過實現(xiàn)CommandLineRunner接口,在spring boot項目啟動后執(zhí)行代碼..."); } }
對比:
相同點:這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執(zhí)行某些方法,都是在SpringApplication 執(zhí)行之后開始執(zhí)行的。
不同點:CommandLineRunner接口可以用來接收字符串?dāng)?shù)組的命令行參數(shù),ApplicationRunner 是使用ApplicationArguments 用來接收參數(shù)的
注意:
1、執(zhí)行順序可以使用注解@Order或者Ordered接口,注解@Order或者接口Ordered的作用是定義Spring IOC容器中Bean的執(zhí)行順序的優(yōu)先級,而不是定義Bean的加載順序,Bean的加載順序不受@Order或Ordered接口的影響;
2、當(dāng)項目中同時實現(xiàn)了ApplicationRunner和CommondLineRunner接口時,可使用Order注解或?qū)崿F(xiàn)Ordered接口來指定執(zhí)行順序,值越小,越優(yōu)先執(zhí)行
3、注解有一個int類型的參數(shù),可以不傳,默認(rèn)是最低優(yōu)先級;
以上就是Spring Boot 項目啟動自動執(zhí)行方法的兩種實現(xiàn)方式的詳細(xì)內(nèi)容,更多關(guān)于Spring Boot 項目啟動自動執(zhí)行方法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
基于newFixedThreadPool實現(xiàn)多線程案例
這篇文章主要介紹了基于newFixedThreadPool實現(xiàn)多線程案例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下2020-11-11Spring JdbcTemplate實現(xiàn)添加與查詢方法詳解
JdbcTemplate是Spring框架自帶的對JDBC操作的封裝,目的是提供統(tǒng)一的模板方法使對數(shù)據(jù)庫的操作更加方便、友好,效率也不錯,這篇文章主要介紹了Spring?JdbcTemplate執(zhí)行數(shù)據(jù)庫操作,需要的朋友可以參考下2022-11-11Spring Security Oauth2.0 實現(xiàn)短信驗證碼登錄示例
本篇文章主要介紹了Spring Security Oauth2.0 實現(xiàn)短信驗證碼登錄示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-01-01