在開發(fā)的過程中,有時需要在應用啟動后自動進行一些操作,比如:項目啟動前初始化資源文件、初始化線程池、提前加載加密證書等等。下邊介紹兩個接口CommandLineRunner 和 ApplicationRunner 來滿足我們的需求,它們會在spring Bean初始化之后SpringApplication run方法執(zhí)行之前調用,如果需要指定執(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í)行結果
MyApplicationRunner1MyCommandLineRunner1MyApplicationRunner2MyCommandLineRunner2MyApplicationRunner3MyCommandLineRunner3