一、CommandLineRunner的作用
項目啟動后,執行run方法中的代碼。
如下所示:
package org.springboot.sample.runner; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; @Component public class MyStartupRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務啟動執行,執行加載數據等操作<<<<<<<<<<<<<"); } }
二、如果有多個類實現CommandLineRunner接口,如何保證順序
使用@Order 注解,通過源碼查看,order的值越小優先級越高
如下所示:
package org.springboot.sample.runner; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(value=2) public class MyStartupRunner1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務啟動執行 2222 <<<<<<<<<<<<<"); } }
三、CommandLineRunner接口在SpringBoot啟動時執行的順序
CommandLineRunner接口的run()方法會在spring bean初始化之后,SpringApplication run之前執行,可以控制在項目啟動前初始化資源文件,比如初始化線程池,提前加載好加密證書等
四、Springboot中的類似接口
ApplicationRunner