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