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