在使用SpringBoot建構項目時,我們通常有一些預先資料的加載。那麼SpringBoot提供了一個簡單的方式來實作–CommandLineRunner。
CommandLineRunner是一個接口,我們需要時,隻需實作該接口就行。如果存在多個加載的資料,我們也可以使用@Order注解來排序。
案例:
分别定義了一個資料加載類MyStartupRunner1,排序為2;以及另一個資料加載類MyStartupRunner2,排序為1。
@Component
@Order(value = )
public class MyStartupRunner1 implements CommandLineRunner{
@Override
public void run(String... strings) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服務啟動執行,執行加載資料等操作 MyStartupRunner1 order 2 <<<<<<<<<<<<<");
}
}
@Component
@Order(value = )
public class MyStartupRunner2 implements CommandLineRunner {
@Override
public void run(String... strings) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服務啟動執行,執行加載資料等操作 MyStartupRunner2 order 1 <<<<<<<<<<<<<");
}
}
啟動服務,可以看到order為1的先加載,再加載order為2的,由此可簡單實作資料有序預加載。