一次。。有人问我:“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加载完成-------------------------"); } }