Spring Boot 啟動加載數(shù)據(jù) CommandLineRunner,非常有用

實(shí)際應(yīng)用中,我們會有在項(xiàng)目服務(wù)啟動的時候就去加載一些數(shù)據(jù)或做一些事情這樣的需求。為了解決這樣的問題,spring Boot為我們提供了一個方法,通過實(shí)現(xiàn)接口 CommandLineRunner 來實(shí)現(xiàn)。

很簡單,只需要一個類就可以,無需其他配置,創(chuàng)建實(shí)現(xiàn)接口 CommandLineRunner 的類。

package org.springboot.sample.runner;

import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 服務(wù)啟動執(zhí)行
 *
 * @author   單紅宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2016年1月9日
 */
@Component
public class MyStartupRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
    }

}

Spring Boot應(yīng)用程序在啟動后,會遍歷CommandLineRunner接口的實(shí)例并運(yùn)行它們的run方法。也可以利用@Order注解(或者實(shí)現(xiàn)Order接口)來規(guī)定所有CommandLineRunner實(shí)例的運(yùn)行順序,如下我們使用@Order 注解來定義執(zhí)行順序。

package org.springboot.sample.runner;

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

/**
 * 服務(wù)啟動執(zhí)行
 *
 * @author   單紅宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2016年1月9日
 */
@Component
@Order(value=2)
public class MyStartupRunner1 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服務(wù)啟動執(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;

/**
 * 服務(wù)啟動執(zhí)行
 *
 * @author   單紅宇(365384722)
 * @myblog  http://blog.csdn.net/catoop/
 * @create    2016年1月9日
 */
@Component
@Order(value=1)
public class MyStartupRunner2 implements CommandLineRunner {

    @Override
    public void run(String... args) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 22222222 <<<<<<<<<<<<<");
    }

}

啟動程序后,控制臺輸出結(jié)果為:

>>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 22222222 <<<<<<<<<<<<<
>>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行,執(zhí)行加載數(shù)據(jù)等操作 11111111 <<<<<<<<<<<<<

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

原文連接:http://blog.csdn.net/catoop/article/details/50501710

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容