CommandLineRunner接口會在容器啟動成功后被回調杨赤。若有多個自定義CommandLineRunner接口句葵,我們可以通過@Order注解/實現(xiàn)Ordered接口控制它們執(zhí)行的先后順序
實現(xiàn)步驟
1)編寫CommandLineRunner
實現(xiàn)類,將其加入spring容器中
@Component
public class ServerSuccessReport implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("======應用啟動成功======");
}
}
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();
}
}
我們看到廊遍,當輸出
======應用啟動成功======
后嬉愧,應用提示我們花費了9s時間,然后因為我們執(zhí)行了context.close()
方法喉前,應用提示我們正在關閉英染。我們會發(fā)現(xiàn),CommandLineRunner接口的確是在容器初始化成功后被回調的被饿。
@Order
定義CommandLineRunner
執(zhí)行順序
這個較為簡單四康,本文不多描述,@Order
注解中的數(shù)越小狭握,執(zhí)行的優(yōu)先級越高