前言:spring boot项目启动后,需要初始化一些数据如何实现?今天面试时碰到的一个问题记录,及解决方案!!!
方案1、自定义类实现CommandLineRunner接口,重写run()方法
/** * @description:springboot项目启动后初始化配置类 * @author: Amos * @email: lwh@gmail.com * @date: 2022/3/28 15:44 */ @Slf4j @Component @Order(2) public class ProjectRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { log.info("*** ProjectRunner ***"); ProjectRunner.projectRunner(); } public static String projectRunner() { return "ProjectRunner项目启动测试"; } }
方案2、自定义类实现ApplicationRunner 接口,重写run()方法
/** * @description:springboot项目启动后初始化配置类 * @author: Amos * @email: lwh@gmail.com * @date: 2022/3/28 15:46 */ @Component @Order(3) @Slf4j public class Application2Runner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { log.info("*** Application2Runner ***"); Application2Runner.run(); } public static String run() { return "Application2Runner启动完毕"; } }
控制台打印:
[restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with ... [restartedMain] com.stream.Java8StreamApplication : Started Java8StreamApplication in 2.347 seconds ...
[restartedMain] com.stream.config.ProjectRunner : *** ProjectRunner *** [restartedMain] com.stream.config.Application2Runner : *** Application2Runner ***
总结:
1)若有多个代码段需要执行,使用@Order注解设置执行的顺序
2)CommandLineRunner和ApplicationRunner两个接口除了参数不同,其他基本相同
3)CommandLineRunner和ApplicationRunner执行时机为容器启动完成的时候