springboot 中CommandLineRunner接口的作用
點擊上方藍色字體,選擇“標星公眾號”
優(yōu)質(zhì)文章,第一時間送達
? 作者?|??奮斗1314?
來源 |? urlify.cn/quy222
先看CommandLineRunner接口的API:
import?org.springframework.core.annotation.Order;
public?interface?CommandLineRunner?{
????/**
?????* Callback used to run the bean.
?????* @param?args incoming main method arguments
?????* @throws?Exception on error
?????*/
????void?run(String... args)?throws?Exception;
}平常開發(fā)中有可能需要實現(xiàn)在項目啟動后執(zhí)行的功能,SpringBoot提供的一種簡單的實現(xiàn)方案就是添加一個model并實現(xiàn)CommandLineRunner接口,實現(xiàn)功能的代碼放在實現(xiàn)的run方法中。
eg:
import?org.springframework.boot.CommandLineRunner;
import?org.springframework.stereotype.Component;
@Component
public?class?StartupRunner?implements?CommandLineRunner{
????@Override
????public?void?run(String... args)?throws?Exception {
????????System.out.println(">>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
????}
}啟動截圖示例:

如果有多個類實現(xiàn)CommandLineRunner接口,如何保證順序:
SpringBoot在項目啟動后會遍歷所有實現(xiàn)CommandLineRunner的實體類并執(zhí)行run方法,如果需要按照一定的順序去執(zhí)行,那么就需要在實體類上使用一個@Order注解【 @Order(value=1..)】(或者實現(xiàn)Order接口)來表明順序.
eg1:
import?org.springframework.boot.CommandLineRunner;
import?org.springframework.core.annotation.Order;
import?org.springframework.stereotype.Component;
@Component
@Order(value=1)
public class StartupRunnerOne implements CommandLineRunner{
????@Override
????public void run(String... args) throws Exception {
????????System.out.println(">>>>>>>>>>>>>>>服務(wù)啟動第一個開始執(zhí)行的任務(wù),執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
????}
}eg2:
import?org.springframework.boot.CommandLineRunner;
import?org.springframework.core.annotation.Order;
import?org.springframework.stereotype.Component;
@Component
@Order(value=2)
public class StartupRunnerTwo implements CommandLineRunner{
????@Override
????public void run(String... args) throws Exception {
????????System.out.println(">>>>>>>>>>>>>>>服務(wù)第二順序啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
????}
}
粉絲福利:108本java從入門到大神精選電子書領(lǐng)取
???
?長按上方鋒哥微信二維碼?2 秒 備注「1234」即可獲取資料以及 可以進入java1234官方微信群
感謝點贊支持下哈?
評論
圖片
表情
