若是你須要在SpringApplication啓動後執行特殊的代碼,你能夠實現ApplicationRunner或CommandLineRunner接口,這兩個接口工做方式基本上同樣,都是提供單一的run方法,該方法是在容器啓動完成的時候執行,而CommandLineRunner接口可以訪問string數組類型的應用參數,而ApplicationRunner使用的是上面描述過的ApplicationArguments接口。java
ApplicationRunnerspring
@FunctionalInterface public interface ApplicationRunner { void run(ApplicationArguments args) throws Exception; }
CommandLineRunner數組
@FunctionalInterface public interface CommandLineRunner { void run(String... args) throws Exception; }
若是不少定義實現可CommandLineRunner或ApplicationRunner的beans須要指定順序調用,能夠實現org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order註解,好比:ide
@Component @Order(2) public class MyBean1 implements CommandLineRunner{ @Override public void run(String... args) throws Exception { System.out.println("MyBean1初始化了...."); } } @Component @Order(1) public class MyBean2 implements CommandLineRunner{ @Override public void run(String... args) throws Exception { System.out.println("MyBean2初始化了...."); } }
運行Application主程序,控制檯輸出結果:spa