一次。。有人問我:「boot 啓動時 若是想要執行一些任務怎麼作?」html
我特二的回答。放在spring auto 啓動配置項裏面 而後在spring容器啓動的時候注入。或者使用動態代理。作切面。java
雖然上述方式貌似能夠執行。但有點複雜。其實boot提供了一種啓動後就作的任務操做。spring
看源碼說明爲:springboot
Spring Batch jobs. Runs all jobs in the surrounding context by default. Can also be used to launch a specific job
by providing a jobName。dom
即,在spring容器啓動的時候就開始批處理一些任務。是隨spring啓動而加載運行的。ide
使用方式:自定義一個model 實現該及接口並重寫run 方法url
package org.springboot.sample.runner;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;spa
@Component
public class MyStartupRunner implements CommandLineRunner {.net
@Override
public void run(String... args) throws Exception {
System.out.println(">>>>>>>>>>>>>>>服務啓動執行,執行加載數據等操做<<<<<<<<<<<<<");
}代理
}
===========若是有多個類實現CommandLineRunner接口,如何保證順序??? @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(">>>>>>>>>>>>>>>服務啓動執行 2222 <<<<<<<<<<<<<");
}
}
```
```
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(">>>>>>>>>>>>>>>服務啓動執行 111111 <<<<<<<<<<<<<");
}
}
```
> 控制檯顯示
```
>>>>>>>>>>>>>>>服務啓動執行 11111111 <<<<<<<<<<<<<
>>>>>>>>>>>>>>>服務啓動執行 22222222## 標題 ## <<<<<<<<<<<<<
```
> 根據控制檯結果可判斷,@Order 註解的執行優先級是按value值從小到大順序。
改接口經常使用語 boot 啓動初始化時 加載一些配置常量。好比一些三方的訪問接口配置常量。
例如:
package com.big.config; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.CommandLineRunner; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import lombok.Getter; @Component @Getter public class RiskConstants implements CommandLineRunner{ @Autowired private Environment env; /**常數項配置*/ public static final String TD_URL_DOMAIN = ""; @Override public void run(String... args) throws Exception { RiskConstants.TD_URL_DOMAIN = env.getProperty("t.url.domain"); System.out.println("===============配置文件 config加載完成-------------------------"); } }