Spring Boot 啟動加載數(shù)據(jù) CommandLineRunner的使用
實際應用中,我們會有在項目服務啟動的時候就去加載一些數(shù)據(jù)或做一些事情這樣的需求。
為了解決這樣的問題,spring Boot 為我們提供了一個方法,通過實現(xiàn)接口 CommandLineRunner 來實現(xiàn)。
很簡單,只需要一個類就可以,無需其他配置。
創(chuàng)建實現(xiàn)接口 CommandLineRunner 的類
package org.springboot.sample.runner; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * 服務啟動執(zhí)行 * * @author 單紅宇(365384722) * @create 2016年1月9日 */ @Component public class MyStartupRunner1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<"); } }
Spring Boot應用程序在啟動后,會遍歷CommandLineRunner接口的實例并運行它們的run方法。也可以利用@Order注解(或者實現(xiàn)Order接口)來規(guī)定所有CommandLineRunner實例的運行順序。
如下我們使用@Order 注解來定義執(zhí)行順序。
package org.springboot.sample.runner; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 服務啟動執(zhí)行 * * @author 單紅宇(365384722) * @create 2016年1月9日 */ @Component @Order(value=2) public class MyStartupRunner1 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 11111111 <<<<<<<<<<<<<"); } }
package org.springboot.sample.runner; import org.springframework.boot.CommandLineRunner; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; /** * 服務啟動執(zhí)行 * * @author 單紅宇(365384722) * @create 2016年1月9日 */ @Component @Order(value=1) public class MyStartupRunner2 implements CommandLineRunner { @Override public void run(String... args) throws Exception { System.out.println(">>>>>>>>>>>>>>>服務啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 22222222 <<<<<<<<<<<<<"); } }
啟動程序后,控制臺輸出結果為:
>>>>>>>>>>>>>>>服務啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 22222222 <<<<<<<<<<<<<
>>>>>>>>>>>>>>>服務啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 11111111 <<<<<<<<<<<<<
根據(jù)控制臺結果可判斷,@Order 注解的執(zhí)行優(yōu)先級是按value值從小到大順序。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
spring cloud gateway如何獲取請求的真實地址
這篇文章主要介紹了spring cloud gateway如何獲取請求的真實地址問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2023-05-05IDEA中創(chuàng)建maven項目引入相關依賴無法下載jar問題及解決方案
這篇文章主要介紹了IDEA中創(chuàng)建maven項目引入相關依賴無法下載jar問題及解決方案,本文通過圖文并茂的形式給大家分享解決方案,需要的朋友可以參考下2020-07-07Spring?Boot中KafkaListener的介紹、原理和使用方法案例詳解
本文介紹了Spring Boot中 @KafkaListener 注解的介紹、原理和使用方法,通過本文的介紹,我們希望讀者能夠更好地理解Spring Boot中 @KafkaListener 注解的使用方法,并在項目中更加靈活地應用2023-09-09Spring-boot結合Shrio實現(xiàn)JWT的方法
這篇文章主要介紹了Spring-boot結合Shrio實現(xiàn)JWT的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-05-05基于Springboot的漫畫網(wǎng)站平臺設計與實現(xiàn)
本文將基于Springboot實現(xiàn)開發(fā)一個漫畫主題的網(wǎng)站,實現(xiàn)一個比漂亮的動漫連載的網(wǎng)站系統(tǒng),界面設計優(yōu)雅大方,比較適合做畢業(yè)設計和課程設計使用,需要的可以參考一下2022-08-08

SpringBoot自定義工具類實現(xiàn)Excel數(shù)據(jù)存入MySQL數(shù)據(jù)庫