在开发的过程中,有时需要在应用启动后自动进行一些操作,比如:项目启动前初始化资源文件、初始化线程池、提前加载加密证书等等。下边介绍两个接口CommandLineRunner 和 ApplicationRunner 来满足我们的需求,它们会在spring Bean初始化之后SpringApplication run方法执行之前调用,如果需要指定执行顺序,可以使用@Order注解,值越小越先执行。
执行顺序:
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”); }}
执行结果
MyApplicationRunner1MyCommandLineRunner1MyApplicationRunner2MyCommandLineRunner2MyApplicationRunner3MyCommandLineRunner3