若是你须要在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