您好,登錄后才能下訂單哦!
今天小編給大家分享一下springboot項(xiàng)目啟動(dòng)后的執(zhí)行方法有哪些的相關(guān)知識(shí)點(diǎn),內(nèi)容詳細(xì),邏輯清晰,相信大部分人都還太了解這方面的知識(shí),所以分享這篇文章給大家參考一下,希望大家閱讀完這篇文章后有所收獲,下面我們一起來(lái)了解一下吧。
ApplicationListener< ContextRefreshedEvent> 不推薦
ApplicationListener 推薦
CommandLineRunner 推薦
實(shí)現(xiàn)ApplicationListener接口,并實(shí)現(xiàn) onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent)方法
@Service public class SearchReceive implements ApplicationListener<ContextRefreshedEvent> { @Override public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) { if (contextRefreshedEvent.getApplicationContext().getParent() == null) {//保證只執(zhí)行一次 //需要執(zhí)行的方法 } } }
ApplicationListener和CommandLineRunner兩個(gè)接口是springBoot提供用來(lái)在spring容器加載完成后執(zhí)行指定方法。兩個(gè)接口區(qū)別主要是入?yún)⒉煌?/p>
實(shí)現(xiàn)ApplicationRunner接口
@Component @Order(value = 1) public class AfterRunner implements ApplicationRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("執(zhí)行方法"); } }
實(shí)現(xiàn)CommandLineRunner接口
@Component @Order(value = 2) public class CommandLineRunnerImpl implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println("執(zhí)行方法"); } }
注:如果同時(shí)implements ApplicationListener和CommandLineRunner兩個(gè)接口,ApplicationRunner接口的方法先執(zhí)行,CommandLineRunner后執(zhí)行;
@Slf4j @Component public class RunnerTest implements ApplicationRunner, CommandLineRunner { @Override public void run(ApplicationArguments args) throws Exception { System.out.println("服務(wù)啟動(dòng)RunnerTest ApplicationRunner執(zhí)行啟動(dòng)加載任務(wù)..."); } @Override public void run(String... args) throws Exception { System.out.println("服務(wù)啟動(dòng)RunnerTest CommandLineRunner 執(zhí)行啟動(dòng)加載任務(wù)..."); } } }
當(dāng)項(xiàng)目中同時(shí)實(shí)現(xiàn)了ApplicationRunner和CommondLineRunner接口時(shí),可使用Order注解或?qū)崿F(xiàn)Ordered接口來(lái)指定執(zhí)行順序,值越小越先執(zhí)行。
SpringApplication 的run方法會(huì)執(zhí)行afterRefresh方法。
afterRefresh方法會(huì)執(zhí)行callRunners方法。
callRunners方法會(huì)調(diào)用所有實(shí)現(xiàn)ApplicationRunner和CommondLineRunner接口的方法。
以上就是“springboot項(xiàng)目啟動(dòng)后的執(zhí)行方法有哪些”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家閱讀完這篇文章都有很大的收獲,小編每天都會(huì)為大家更新不同的知識(shí),如果還想學(xué)習(xí)更多的知識(shí),請(qǐng)關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。