前言
在我们用springboot搭建项目的时候,有时候会碰到在项目启动时初始化一些操作的需求,针对这种需求springboot(spring)为我们提供了以下几种方案供我们选择:
- ApplicationRunner与CommandLineRunner接口
- Spring Bean初始化的InitializingBean,init-method和PostConstruct
- Spring的事件机制
ApplicationRunner与CommandLineRunner
如果需要在SpringApplication启动时执行一些特殊的代码,你可以实现ApplicationRunner或CommandLineRunner接口,这两个接口工作方式相同,都只提供单一的run方法,而且该方法仅在SpringApplication.run(…)完成之前调用,更准确的说是在构造SpringApplication实例完成之后调用run()的时候,具体分析见后文,所以这里将他们分为一类。
(1)ApplicationRunner
构造一个类实现ApplicationRunner接口
@Component
public class ApplicationRunnerTest implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner");
}
}
项目启动测试结果如图:
(2)CommandLineRunner
对于这两个接口而言,我们可以通过Order注解或者使用Ordered接口来指定调用顺序,@Order()中的值越小,优先级越高
@Component
@Order(1)
public class CommandLineRunnerTest implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner...");
}
}
当然我们也可以同时使用ApplicationRunner和CommandLineRunner,默认情况下前者比后者先执行,但是这没有必要,使用一个就好了