在 SpringBoot 工程 啟動(dòng)后, 執(zhí)行方法的五種方式:
1、實(shí)現(xiàn) CommandLineRunner 接口
項(xiàng)目初始化完畢后,才會(huì)調(diào)用方法,提供服務(wù)
@Component
public class StartInit2 implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("CommandLineRunner====================");
}
}
2、實(shí)現(xiàn) ApplicationRunner 接口
同 CommandLineRunner。只是傳參格式不一樣。CommandLineRunner:沒有任何限制;ApplicationRunner:key-value
@Component
public class StartInit3 implements ApplicationRunner {
@Override
public void run(ApplicationArguments args) {
System.out.println("ApplicationRunner=================");
}
}
3、實(shí)現(xiàn) ApplicationListener 接口
項(xiàng)目初始化完畢后,才會(huì)調(diào)用方法,提供服務(wù)。注意監(jiān)聽的事件,通常是 ApplicationStartedEvent 或者 ApplicationReadyEvent,其他的事件可能無法注入 bean。
@Component
public class StartInit4 implements ApplicationListener<ApplicationStartedEvent> {
@Override
public void onApplicationEvent(ApplicationStartedEvent event) {
System.out.println("ApplicationListener================ApplicationStartedEvent");
}
}
- 如果監(jiān)聽的是
ApplicationStartedEvent
事件,則 ApplicationListener 一定會(huì)在 CommandLineRunner 和 ApplicationRunner 之前執(zhí)行; - 如果監(jiān)聽的是
ApplicationReadyEvent
事件,則 ApplicationListener 一定會(huì)在 CommandLineRunner 和 ApplicationRunner 之后執(zhí)行;
順序:
默認(rèn)是 ApplicationRunner
先執(zhí)行,如果雙方指定了@Order
則按照 @Order
的大小順序執(zhí)行,小的先執(zhí)行。
原理:
- SpringApplication 的run方法會(huì)執(zhí)行afterRefresh方法。
- afterRefresh方法會(huì)執(zhí)行callRunners方法。
- callRunners方法會(huì)調(diào)用所有實(shí)現(xiàn)ApplicationRunner和CommondLineRunner接口的方法callRunners方法會(huì)調(diào)用所有實(shí)現(xiàn)ApplicationRunner和CommondLineRunner接口的方法
4、@PostConstruct 注解
在項(xiàng)目初始化過程中,就會(huì)調(diào)用此方法。如果業(yè)務(wù)邏輯執(zhí)行很耗時(shí),可能會(huì)導(dǎo)致項(xiàng)目啟動(dòng)失敗。
@Component
public class StartInit {
@PostConstruct
public void init() {
System.out.println("@PostConstruct===============================");
}
}
5、實(shí)現(xiàn) InitializingBean 接口文章來源:http://www.zghlxwxcb.cn/news/detail-404064.html
項(xiàng)目啟動(dòng)時(shí),調(diào)用此方法文章來源地址http://www.zghlxwxcb.cn/news/detail-404064.html
@Component
public class StartInit6 implements InitializingBean {
@Override
public void afterPropertiesSet() {
System.out.println("InitializingBean====================");
}
}
到了這里,關(guān)于【SpringBoot】 啟動(dòng)后執(zhí)行方法的五種方式的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!