SpringBoot中CommandLineRunner是怎樣的

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

成都創(chuàng)新互聯(lián)是專業(yè)的惠東網(wǎng)站建設(shè)公司,惠東接單;提供成都網(wǎng)站制作、網(wǎng)站建設(shè)、外貿(mào)網(wǎng)站建設(shè),網(wǎng)頁設(shè)計,網(wǎng)站設(shè)計,建網(wǎng)站,PHP網(wǎng)站建設(shè)等專業(yè)做網(wǎng)站服務;采用PHP框架,可快速的進行惠東網(wǎng)站開發(fā)網(wǎng)頁制作和功能擴展;專業(yè)做搜索引擎喜愛的網(wǎng)站,專業(yè)的做網(wǎng)站團隊,希望更多企業(yè)前來合作!

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)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對創(chuàng)新互聯(lián)的支持。

文章名稱:SpringBoot中CommandLineRunner是怎樣的
文章來源:http://muchs.cn/article32/ghecsc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供云服務器自適應網(wǎng)站、定制網(wǎng)站、小程序開發(fā)、網(wǎng)頁設(shè)計公司、App開發(fā)

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站網(wǎng)頁設(shè)計