Springboot項目啟動成功后可通過五種方式繼續(xù)執(zhí)行
- 實現(xiàn)CommandLineRunner接口
項目初始化完畢后,才會調(diào)用方法,提供服務(wù)
@Component public class StartRunner implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("CommandLineRunner===================="); } }
- 實現(xiàn)ApplicationRunner接口
同 CommandLineRunner。只是傳參格式不一樣。CommandLineRunner:沒有任何限制;ApplicationRunner:key-value
@Component public class StartRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) { System.out.println("ApplicationRunner================="); } }
- 實現(xiàn)ApplicationListener接口
項目初始化完畢后,才會調(diào)用方法,提供服務(wù)。注意監(jiān)聽的事件,通常是 ApplicationStartedEvent 或者 ApplicationReadyEvent,其他的事件可能無法注入 bean。
@Component public class StartListener implements ApplicationListener<ApplicationStartedEvent> { @Override public void onApplicationEvent(ApplicationStartedEvent event) { System.out.println("ApplicationListener================ApplicationStartedEvent"); } }
如果監(jiān)聽的是 ApplicationStartedEvent 事件,則 ApplicationListener 一定會在 CommandLineRunner 和 ApplicationRunner 之前執(zhí)行;
如果監(jiān)聽的是 ApplicationReadyEvent 事件,則 ApplicationListener 一定會在 CommandLineRunner 和 ApplicationRunner 之后執(zhí)行;
順序:
默認是 ApplicationRunner 先執(zhí)行,如果雙方指定了@Order 則按照 @Order的大小順序執(zhí)行,小的先執(zhí)行
- @PostConstruct注解
在項目初始化過程中,就會調(diào)用此方法。如果業(yè)務(wù)邏輯執(zhí)行很耗時,可能會導(dǎo)致項目啟動失敗。
@Component public class StartInit { @PostConstruct public void init() { System.out.println("@PostConstruct==============================="); } }
- 實現(xiàn)InitalizingBean接口
項目啟動時,調(diào)用此方法
@Component public class StartSet implements InitializingBean { @Override public void afterPropertiesSet() { System.out.println("InitializingBean===================="); } }
到此這篇關(guān)于Springboot項目啟動成功后可通過五種方式繼續(xù)執(zhí)行的文章就介紹到這了,更多相關(guān)Springboot啟動成功后繼續(xù)執(zhí)行內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章

java實現(xiàn)學(xué)生成績錄入系統(tǒng)

Java IText異常NoClassDefFoundError: org/bouncycastle