在使用SpringBoot
搭建项目时,有时需要在项目启动时做一些事情,比如初始化数据库、加载配置文件等等。
SpringBoot
为我们提供了以下几种方案供我们选择:
- 实现
ApplicationRunner
接口或者实现CommandLineRunner
接口 - 利用
Spring
的事件机制
1 实现ApplicationRunner或CommandLineRunner接口
如果需要在Application
启动的时候执行一些代码,可以通过实现SpringBoot
提供的ApplicationRunner
和CommandLineRunner
接口来达到目的。
ApplicationRunner
和CommandLineRunner
在SpringApplication.run()
结束之前,在所有的beans
加载完成之后执行。用于执行一些初始化操作(如加载缓存、读取配置文件、创建线程池等)。
1.1 源码
这两个接口工作方式相同,都只提供一个run
方法,源码如下:
ApplicationRunner
源码:
@FunctionalInterface
public interface ApplicationRunner {
void run(ApplicationArguments args) throws Exception;
}
CommandLineRunner
源码:
@FunctionalInterface
public interface CommandLineRunner {
void run(String... args) throws Exception;
}
不同的是,ApplicationRunner
通过ApplicationArguments
接收启动参数,对原始参数进行了封装。CommandLineRunner
通过String
数组接收启动参数,保留原始参数。
1.2 使用方式
我们可以通过实现这两个接口之一,并使用@Component
注解将实现类注册为bean
。
/**
* Application启动时进行一些初始化
*/
@Component
public class AppInit implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("进行一些初始化操作...");
}
}
还可以通过@Order
注解或者实现Ordered
接口来指定多个初始化类中run
方法的调用顺序。数值越小,优选级越高。
/**
* Application启动时进行一些初始化
*/
@Component
@Order(1)
public class AppInit1 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("order = 1, 进行一些初始化操作...");
}
}
/**
* Application启动时进行一些初始化
*/
@Component
@Order(2)
public class AppInit2 implements CommandLineRunner {
@Override
public void run(String..<