摘要:有时启动springboot项目后需要执行一些方法初始化,如资源加载、数据准备等,首先不能放在main方法中SpringApplication.run()之前,因为此时bean还未初始化,除非你不使用bean,当然也不能放其后,因为run方法执行后启动tomcat会阻塞在端口监听,run方法后的代码不会执行。
一、如何实现
有两种方法。实现 ApplicationRunner
或 CommandLineRunner
接口。
示例:
@Component
public class Bootstrap implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
// 项目启动时自动执行此方法
}
}