前言: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執行時機為容器啟動完成的時候