Spring Boot提供了兩種 「開機自啓動」 的方式,ApplicationRunner和CommandLineRunnerapp
這兩種方式的目的是爲了知足,在容器啓動時like執行某些方法。咱們能夠經過實現ApplicationRunner或者CommandLineRunner來實現,他們都是在SpringAppliaction執行以後開始執行的。這個特性能夠讓咱們自定義一些在容器啓動時須要初始化的邏輯ide
ApplicationRunner接口:spa
官方doc:code
Interface used to indicate that a bean should run when it is contained within a SpringApplication. Multiple ApplicationRunner beans can be defined within the same application context and can be ordered using the Orderedblog
當該接口包含在SpringApplication中時執行。多個ApplicationRunner經過Order直接進行排序:排序
/** * 初始化類 */ @Order(1) // @Order註解能夠改變執行順序,越小越先執行 @Component public class MyApplicationRunner1 implements ApplicationRunner { /** * 會在服務啓動完成後當即執行 */ @Override public void run(ApplicationArguments arg0) throws Exception { System.out.println("MyApplicationRunner1----" + arg0); } }
/** * 初始化類 */ @Order(2) @Component public class MyApplicationRunner2 implements ApplicationRunner { /** * 會在服務啓動完成後當即執行 */ @Override public void run(ApplicationArguments arg0) throws Exception { System.out.println("MyApplicationRunner2----" + arg0); } }
容器啓動後的運行結果:接口
能夠看到多個ApplicationRunner執行順序是按照Order中的值執行的,而且每一個的入參都是同一個ApplicationArguments實例(具體緣由後面分析)ip
CommandLineRunner接口:源碼
兩者的官方doc基本同樣,區別在於接收的參數不同it
/** * 初始化類 */ @Order(1) // @Order註解能夠改變執行順序,越小越先執行 @Component public class MyCommandLineRunner1 implements CommandLineRunner { /** * 會在服務啓動完成後當即執行 */ @Override public void run(String... args) throws Exception { System.out.println("MyCommandLineRunner1----" + args); } }
/** * 初始化類 */ @Order(2) @Component public class MyCommandLineRunner2 implements CommandLineRunner { /** * 會在服務啓動完成後當即執行 */ @Override public void run(String... args) throws Exception { System.out.println("MyCommandLineRunner2----" + args); } }
容器啓動後的運行結果:
能夠看到多個CommandLineRunner的執行效果跟ApplicationRunner如出一轍
最後看下源碼:
SpringApplication啓動時,會執行其run方法中的afterRefresh方法:
在afterRefresh中能夠看到這兩個接口被執行,而且每一個ApplicationRunner或CommandLineRunner實例都是用的同一個入參: