Spring Boot 項目啟動自動執行方法的兩種實現方式
springboot項目啟動成功后執行一段代碼,如系統常量,配置、代碼集等等初始化操作;執行多個方法時,執行順序使用Order注解或Order接口來控制。
Springboot給我們提供了兩種方式
第一種實現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('通過實現ApplicationRunner接口,在spring boot項目啟動后執行代碼...');}}第二種實現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('通過實現CommandLineRunner接口,在spring boot項目啟動后執行代碼...');}}對比:
相同點:這兩種方法提供的目的是為了滿足,在項目啟動的時候立刻執行某些方法,都是在SpringApplication 執行之后開始執行的。
不同點:CommandLineRunner接口可以用來接收字符串數組的命令行參數,ApplicationRunner 是使用ApplicationArguments 用來接收參數的
注意:1、執行順序可以使用注解@Order或者Ordered接口,注解@Order或者接口Ordered的作用是定義Spring IOC容器中Bean的執行順序的優先級,而不是定義Bean的加載順序,Bean的加載順序不受@Order或Ordered接口的影響;
2、當項目中同時實現了ApplicationRunner和CommondLineRunner接口時,可使用Order注解或實現Ordered接口來指定執行順序,值越小,越優先執行
3、注解有一個int類型的參數,可以不傳,默認是最低優先級;
以上就是Spring Boot 項目啟動自動執行方法的兩種實現方式的詳細內容,更多關于Spring Boot 項目啟動自動執行方法的資料請關注好吧啦網其它相關文章!
相關文章: