先看CommandLineRunner接口的API:
import org.springframework.core.annotation.Order;
public interface CommandLineRunner {
/**
* Callback used to run the bean.
* @param args incoming main method arguments
* @throws Exception on error
*/
void run(String... args) throws Exception;
}
平常開發(fā)中有可能需要實現(xiàn)在項目啟動后執(zhí)行的功能,SpringBoot提供的一種簡單的實現(xiàn)方案就是添加一個model并實現(xiàn)CommandLineRunner接口俊嗽,實現(xiàn)功能的代碼放在實現(xiàn)的run方法中吏砂。
ex:
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
@Component
public class StartupRunner implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服務(wù)啟動執(zhí)行和簸,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
}
}
啟動截圖示例:
TIM圖片20190225161118.png
如果有多個類實現(xiàn)CommandLineRunner接口贺待,如何保證順序:
SpringBoot在項目啟動后會遍歷所有實現(xiàn)CommandLineRunner的實體類并執(zhí)行run方法,如果需要按照一定的順序去執(zhí)行园欣,那么就需要在實體類上使用一個@Order注解【 @Order(value=1..)】(或者實現(xiàn)Order接口)來表明順序.
ex1:
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value=1)
public class StartupRunnerOne implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服務(wù)啟動第一個開始執(zhí)行的任務(wù)叼风,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
}
}
ex2:
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(value=2)
public class StartupRunnerTwo implements CommandLineRunner{
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服務(wù)第二順序啟動執(zhí)行取董,執(zhí)行加載數(shù)據(jù)等操作<<<<<<<<<<<<<");
}
}
上面兩個類的示例代碼,啟動后執(zhí)行順序看截圖:
TIM圖片20190304135532.png