在日常的Springboot项目开发过程中,我们经常会遇到需要在项目启动后进行一些数据加载,配置初始化等操作,下面是Springboot中常见的一些初始化操作。
方法一:CommandLineRunner接口
自定义类实现CommandLineRunner
接口
@Component
public class InitTest1 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("init test by CommandLineRunner....");
}
}
注意:方法在项目初始化完成之后才会调用。
方法二:ApplicationRunner接口
与CommandLineRunner接口类似,自定义类实现ApplicationRunner
接口
@Component
public class InitTest2 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("init test by ApplicationRunner....");
}
}
注意:方法在项目初始化完成之后才会调用。默认情况下会先调用实现了ApplicationRunner 接口的类,然后才是实现了CommandLineRunner接口的类。
如何指定顺序
对于上述两种方法的实现,当有多个实现类时可以通过@Order
注解或实现Ordered
接口来指定方法的调用顺序。
@Component
//@Order(1)
public class InitTest1 implements CommandLineRunner, Ordered {
@Override
public void run(String... args) throws Exception {
System.out.println("init test by CommandLineRunner....");
}
@Override
public int getOrder() {
return 1;
}
}
@Component
@Order(2)
public class InitTest2 implements ApplicationRunner/*, Ordered*/ {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("init test by ApplicationRunner....");
}
/*@Override
public int getOrder() {
return 2;
}*/
}
注解的属性值/getOrder返回的值越小,方法越先执行。
方法三:采用监听器ApplicationListener监听事件方式
通过自定义监听器在监听到相应事件时调用,通常选择的监听事件为:ApplicationStartedEvent
、ApplicationReadyEvent
、ContextRefreshedEvent
@Component
public class InitTest3 implements ApplicationListener<ApplicationReadyEvent> {
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
System.out.println("init test by ApplicationListener....");
}
}
注意:根据监听的事件类型不同,方法可能在项目初始化开始、过程中、完成后调用,只要触发了该事件就会调用一次,所以选择合适的事件类型也是关键。
- 监听
ApplicationStartedEvent
事件:项目初始化完成之后才会调用,并且在CommandLineRunner和ApplicationRunner之后; - 监听
ApplicationReadyEvent
事件:项目初始化完成之后才会调用,并且在CommandLineRunner和ApplicationRunner之后; - 监听
ContextRefreshedEvent
事件:项目初始化过程中就会调用。
方法四:@PostConstruct注解
在需要调用的初始化方法上用@PostConstruct 注解。
@Component
public class InitTest4 {
@PostConstruct
public void init() {
System.out.println("init test by @PostConstruct....");
}
}
注意:这种方式在项目初始化过程中就会调用。
方法五:InitializingBean接口
自定义类实现InitializingBean
接口
@Component
public class InitTest5 implements InitializingBean {
@Override
public void afterPropertiesSet() throws Exception {
System.out.println("init test by InitializingBean....");
}
}
注意:这种方式在项目初始化过程中就会调用。
方法六:静态代码块
采用静态代码块,但是需要将代码块所在的类定义为Bean,Spring容器在初始化的时候就会执行改代码块。
@Component
public class InitTest6 {
/**
* 静态代码块会随着类的加载而加载,只是加载,还未执行
* 静态代码块会在使用该类的时候优先执行,例如实例化完成之前会调用,调用静态方法之前会先调用...
*/
static {
System.out.println("init test by static block....");
}
}
注意:在项目初始化过程中执行。