Spring Boot 項目啟動自動執(zhí)行方法的兩種實現(xiàn)方式
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 {@Overridepublic 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 {@Overridepublic void run(String... args) throws Exception {System.out.println('通過實現(xiàn)CommandLineRunner接口,在spring boot項目啟動后執(zhí)行代碼...');}}對比:
相同點:這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執(zhí)行某些方法,都是在SpringApplication 執(zhí)行之后開始執(zhí)行的。
不同點:CommandLineRunner接口可以用來接收字符串數(shù)組的命令行參數(shù),ApplicationRunner 是使用ApplicationArguments 用來接收參數(shù)的
注意:1、執(zhí)行順序可以使用注解@Order或者Ordered接口,注解@Order或者接口Ordered的作用是定義Spring IOC容器中Bean的執(zhí)行順序的優(yōu)先級,而不是定義Bean的加載順序,Bean的加載順序不受@Order或Ordered接口的影響;
2、當項目中同時實現(xiàn)了ApplicationRunner和CommondLineRunner接口時,可使用Order注解或?qū)崿F(xiàn)Ordered接口來指定執(zhí)行順序,值越小,越優(yōu)先執(zhí)行
3、注解有一個int類型的參數(shù),可以不傳,默認是最低優(yōu)先級;
以上就是Spring Boot 項目啟動自動執(zhí)行方法的兩種實現(xiàn)方式的詳細內(nèi)容,更多關(guān)于Spring Boot 項目啟動自動執(zhí)行方法的資料請關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
