如題,很多時候,我們都需要在springboot項目啟動后初始化化一些自己的數據
原文地址:https://www.jianshu.com/p/f80f833ab8f6
實現方法有2個。
一、ApplicationRunner
實現ApplicationRunner接口
打上@Component
+implements ApplicationRunner
@Component
public class DemoApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner");
}
}
二、CommandLineRunner
實現CommandLineRunner接口
打上@Component
+implements CommandLineRunner
@Component
public class DemoComLiner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner");
}
}
原理講解
SpringApplication的run方法會執行afterRefresh方法
afterRefresh會觸發callRunners方法
callRunners方法會調用容器里面所有實現了ApplicationRunner、CommandLineRunner接口的方法