Spring Boot 啟動加載數據 CommandLineRunner


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

很簡單,只需要一個類就可以,無需其他配置。 
創建實現接口 CommandLineRunner 的類

 

Spring Boot應用程序在啟動后,會遍歷CommandLineRunner接口的實例並運行它們的run方法。也可以利用@Order注解(或者實現Order接口)來規定所有CommandLineRunner實例的運行順序。

 

package com.hgvip.preworks;

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

/**
 * Created by arnold.zhu on 6/12/2017.
 */
@Component
@Order(value = 1)
public class MyStartupRunner1 implements CommandLineRunner {

    @Override
    public void run(String... strings) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>MyStartupRunner1服務啟動執行,執行加載數據等操作<<<<<<<<<<<<<");
    }

}
package com.hgvip.preworks;

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

/**
 * Created by arnold.zhu on 6/12/2017.
 */
@Component
@Order(value = 2)
public class MyStartupRunner2 implements CommandLineRunner {

    @Override
    public void run(String... strings) throws Exception {
        System.out.println(">>>>>>>>>>>>>>>MyStartupRunner2服務啟動執行,執行加載數據等操作<<<<<<<<<<<<<");
    }
}

 

根據控制台結果可判斷,@Order 注解的執行優先級是按value值從小到大順序。

執行結果:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM