前言
在我們實(shí)際工作中,總會(huì)遇到這樣需求,在項(xiàng)目啟動(dòng)的時(shí)候需要做一些初始化的操作,比如初始化線程池,提前加載好加密證書等。今天就給大家介紹一個(gè) Spring Boot 神器,專門幫助大家解決項(xiàng)目啟動(dòng)初始化資源操作。
這個(gè)神器就是 CommandLineRunner, CommandLineRunner 接口的 Component 會(huì)在所有 SpringBeans都初始化之后, SpringApplication.run()之前執(zhí)行,非常適合在應(yīng)用程序啟動(dòng)之初進(jìn)行一些數(shù)據(jù)初始化的工作。
接下來我們就運(yùn)用案例測試它如何使用,在測試之前在啟動(dòng)類加兩行打印提示,方便我們識別 CommandLineRunner 的執(zhí)行時(shí)機(jī)。
@SpringBootApplicationpublic class CommandLineRunnerApplication { public static void main(String[] args) { System.out.println("The service to start."); SpringApplication.run(CommandLineRunnerApplication.class, args); System.out.println("The service has started."); } }