在開發(fā)的過程中,有時(shí)需要在應(yīng)用啟動(dòng)后自動(dòng)進(jìn)行一些操作,比如:項(xiàng)目啟動(dòng)前初始化資源文件、初始化線程池、提前加載加密證書等等。下邊介紹兩個(gè)接口CommandLineRunner 和 ApplicationRunner 來滿足我們的需求,它們會(huì)在spring Bean初始化之后SpringApplication run方法執(zhí)行之前調(diào)用,如果需要指定執(zhí)行順序,可以使用@Order注解,值越小越先執(zhí)行。
執(zhí)行順序:
ApplicationRunner
@Component@Order(1)public class MyApplicationRunner1 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println(“MyApplicationRunner1”); }}@Component@Order(2)public class MyApplicationRunner2 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println(“MyApplicationRunner2”); }}@Componentpublic class MyApplicationRunner3 implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println(“MyApplicationRunner3”); }}
CommandLineRunner
@Component@Order(1)public class MyCommandLineRunner1 implements CommandLineRunner { @Override public void run(String… args) throws Exception { System.out.println(“MyCommandLineRunner1”); }}@Component@Order(2)public class MyCommandLineRunner2 implements CommandLineRunner { @Override public void run(String… args) throws Exception { System.out.println(“MyCommandLineRunner2”); }}@Componentpublic class MyCommandLineRunner3 implements CommandLineRunner { @Override public void run(String… args) throws Exception { System.out.println(“MyCommandLineRunner3”); }}
執(zhí)行結(jié)果
MyApplicationRunner1MyCommandLineRunner1MyApplicationRunner2MyCommandLineRunner2MyApplicationRunner3MyCommandLineRunner3