溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

SpringBoot中CommandLineRunner是怎樣的

發(fā)布時間:2021-09-29 16:56:16 來源:億速云 閱讀:139 作者:柒染 欄目:云計算

SpringBoot中CommandLineRunner是怎樣的,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

SpringBoot中CommandLineRunner的作用

平常開發(fā)中有可能需要實現(xiàn)在項目啟動后執(zhí)行的功能,SpringBoot提供的一種簡單的實現(xiàn)方案就是添加一個model并實現(xiàn)CommandLineRunner接口,實現(xiàn)功能的代碼放在實現(xiàn)的run方法中
也就是項目一啟動之后,就立即需要執(zhí)行的動作

我們只需要在項目里面簡單的配置,就可以實現(xiàn)這個功能。

簡單例子

package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class MyStartupRunner implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("項目已經(jīng)啟動");
}

}

如果有多個類實現(xiàn)CommandLineRunner接口,如何保證順序

SpringBoot在項目啟動后會遍歷所有實現(xiàn)CommandLineRunner的實體類并執(zhí)行run方法,如果需要按照一定的順序去執(zhí)行,那么就需要在實體類上使用一個@Order注解(或者實現(xiàn)Order接口)來表明順序

package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;


@Component
@Order(value=2)
public class MyStartupRunner1 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("執(zhí)行2");
}

}


package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Component
@Order(value=1)
public class MyStartupRunner2 implements CommandLineRunner {

@Override
public void run(String... args) throws Exception {
System.out.println("執(zhí)行1");
}

}

控制臺顯示

執(zhí)行1
執(zhí)行2

根據(jù)控制臺結(jié)果可判斷,@Order 注解的執(zhí)行優(yōu)先級是按value值從小到大順序。

@Order 作用

就是項目啟動之后,要執(zhí)行的動作是比較的多,那么到底先執(zhí)行哪個,那么就可以利用這個注解限定優(yōu)先級。

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI