springBoot啟動時讓方法自動執(zhí)行的幾種實現(xiàn)方式
在springBoot中我們有時候需要讓項目在啟動時提前加載相應的數(shù)據(jù)或者執(zhí)行某個方法,那么實現(xiàn)提前加載的方式有哪些呢?接下來我?guī)ьI(lǐng)大家逐個解答
1.實現(xiàn)ServletContextAware接口并重寫其setServletContext方法
@Componentpublic class TestStarted implements ServletContextAware { /** * 在填充普通bean屬性之后但在初始化之前調(diào)用 * 類似于initializingbean的afterpropertiesset或自定義init方法的回調(diào) * */ @Override public void setServletContext(ServletContext servletContext) { System.out.println('setServletContext方法'); }}
注意:該方法會在填充完普通Bean的屬性,但是還沒有進行Bean的初始化之前執(zhí)行
2.實現(xiàn)ServletContextListener接口
/** * 在初始化Web應用程序中的任何過濾器或servlet之前,將通知所有servletContextListener上下文初始化。 */ @Override public void contextInitialized(ServletContextEvent sce) { //ServletContext servletContext = sce.getServletContext(); System.out.println('執(zhí)行contextInitialized方法'); }
3.將要執(zhí)行的方法所在的類交個spring容器掃描(@Component),并且在要執(zhí)行的方法上添加@PostConstruct注解或者靜態(tài)代碼塊執(zhí)行
@Componentpublic class Test2 { //靜態(tài)代碼塊會在依賴注入后自動執(zhí)行,并優(yōu)先執(zhí)行 static{ System.out.println('---static--'); } /** * @Postcontruct’在依賴注入完成后自動調(diào)用 */ @PostConstruct public static void haha(){ System.out.println('@Postcontruct’在依賴注入完成后自動調(diào)用'); }}
4.實現(xiàn)ApplicationRunner接口
/** * 用于指示bean包含在SpringApplication中時應運行的接口。可以定義多個applicationrunner bean * 在同一應用程序上下文中,可以使用有序接口或@order注釋對其進行排序。 */ @Override public void run(ApplicationArguments args) throws Exception { System.out.println('ApplicationRunner的run方法'); }
5.實現(xiàn)CommandLineRunner接口
/** * 用于指示bean包含在SpringApplication中時應運行的接口。可以在同一應用程序上下文中定義多個commandlinerunner bean,并且可以使用有序接口或@order注釋對其進行排序。 * 如果需要訪問applicationArguments而不是原始字符串數(shù)組,請考慮使用applicationrunner。 * */ @Override public void run(String... ) throws Exception { System.out.println('CommandLineRunner的run方法'); }
到此這篇關(guān)于springBoot啟動時讓方法自動執(zhí)行的幾種實現(xiàn)方式的文章就介紹到這了,更多相關(guān)springBoot啟動時自動執(zhí)行內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Python3 json模塊之編碼解碼方法講解2. Linux刪除系統(tǒng)自帶版本Python過程詳解3. Python 制作查詢商品歷史價格的小工具4. Python 合并拼接字符串的方法5. python 使用事件對象asyncio.Event來同步協(xié)程的操作6. ASP基礎知識VBScript基本元素講解7. ASP.NET MVC使用jQuery ui的progressbar實現(xiàn)進度條8. Python 利用Entrez庫篩選下載PubMed文獻摘要的示例9. Python sublime安裝及配置過程詳解10. Python字符串到字節(jié)的轉(zhuǎn)換。雙反斜杠問題

網(wǎng)公網(wǎng)安備