描述
在项目启动的过程中执行一些指定的业务逻辑代码,初始化数据,加载某一个配置文件等等,所有在项目启动过程中需要自动执行的业务。
场景
下面是我在开发过程中遇到的几个场景:
- 项目如果集成了其他的服务启动时需要同事启动服务,例如:Netty服务,ftp服务搭建,等等。
- 项目启动时需要进行初始化的配置,例如:初始化某一项信息或者对某一项信息预处理。
- 项目启动跟其他系统需要交互或者读取配置。
方式一:实现ApplicationRunner接口重写run方法逻辑
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
@Component
public class InitatialConfig implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("项目启动初始化");
}
}
方式二:实现CommandLineRunner 接口重写run方法逻辑
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class InitatialConfigCommand implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner:"+"{}"+"接口实现方式重写");
}
}
方式三:使用@PostConstruct注解的方式
@PostConstruct
public void testInitConfig(){
System.out.println("@PostConstruct:"+"{}"+"注解方式实现启动初始化配置");
}
初始化顺序
- @PostConstruct 注解方法
- CommandLineRunner接口实现
- ApplicationRunner接口实现
注意:
当CommandLineRunner或者ApplicationRunner存在多个实现类的同时,可以使用@Order(1)注解进行顺序执行,该注解控制Bean的执行顺序。