ApplicationRunner和CommandLineRunner
如果你需要在SpringApplication启动后执行特殊的代码,你可以实现ApplicationRunner或CommandLineRunner接口,这两个接口工作方式基本上一样,都是提供单一的run方法,该方法是在容器启动完成的时候执行,而CommandLineRunner接口能够访问string数组类型的应用参数,而ApplicationRunner使用的是上面描述过的ApplicationArguments接口。
源码
ApplicationRunner
@FunctionalInterface
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
CommandLineRunner
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
如何指定Bean的初始化顺序?
如果很多定义实现可CommandLineRunner或ApplicationRunner的beans需要指定顺序调用,可以实现org.springframework.core.Ordered接口或使用org.springframework.core.annotation.Order注解,比如:
@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主程序,控制台输出结果: