CommandLineRunner接口會(huì)在容器啟動(dòng)成功后被回調(diào)。若有多個(gè)自定義CommandLineRunner接口,我們可以通過@Order注解/實(shí)現(xiàn)Ordered接口控制它們執(zhí)行的先后順序
實(shí)現(xiàn)步驟
1)編寫CommandLineRunner
實(shí)現(xiàn)類,將其加入spring容器中
@Component
public class ServerSuccessReport implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("======應(yīng)用啟動(dòng)成功======");
}
}
2)執(zhí)行BlogApplication
@SpringBootApplication
public class BlogApplication {
public static void main(String[] args) {
SpringApplication springApplication = new SpringApplication(BlogApplication.class);
ConfigurableApplicationContext context = springApplication.run(args);
context.close();
}
}
console result
我們看到,當(dāng)輸出
======應(yīng)用啟動(dòng)成功======
后,應(yīng)用提示我們花費(fèi)了9s時(shí)間,然后因?yàn)槲覀儓?zhí)行了context.close()
方法,應(yīng)用提示我們正在關(guān)閉。我們會(huì)發(fā)現(xiàn),CommandLineRunner接口的確是在容器初始化成功后被回調(diào)的。
@Order
定義CommandLineRunner
執(zhí)行順序
這個(gè)較為簡單,本文不多描述,@Order
注解中的數(shù)越小,執(zhí)行的優(yōu)先級越高
console result