如題,很多時候囱修,我們都需要在springboot項目啟動后初始化化一些自己的數(shù)據(jù)
實現(xiàn)方法有2個外傅。
一、ApplicationRunner
實現(xiàn)ApplicationRunner接口
打上@Component
+implements ApplicationRunner
@Component
public class DemoApplicationRunner implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) throws Exception {
System.out.println("ApplicationRunner");
}
}
二狡赐、CommandLineRunner
實現(xiàn)CommandLineRunner接口
打上@Component
+implements CommandLineRunner
@Component
public class DemoComLiner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner");
}
}
原理講解
SpringApplication的run方法會執(zhí)行afterRefresh方法
afterRefresh會觸發(fā)callRunners方法
callRunners方法會調(diào)用容器里面所有實現(xiàn)了ApplicationRunner、CommandLineRunner接口的方法