引入maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-batch</artifactId>
</dependency>
SringBatch配置demo类
@Configuration
public class BatchConfiguration {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.tasklet(new Tasklet() {
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) {
return null;
}
})
.build();
}
@Bean
public Job job(Step step1) throws Exception {
return jobBuilderFactory.get("job1")
.incrementer(new RunIdIncrementer())
.start(step1)
.build();
}
}
增加自动配置注解
给SpringBoot启动类增加自动执行注解
这个注解加上之后SpringBoot启动时会制动执行你的所有的Job
@EnableBatchProcessing
在spring配置文件中配置SpringBatch
spring:
batch:
initialize-schema: ALWAYS
table-prefix:
schema:
job:
names:
enabled:
initializer:
enabled:
属性介绍
相关类:org.springframework.boot.autoconfigure.batch.BatchProperties
属性值 | 默认值 | 可选属性 | 说明 |
---|---|---|---|
initialize-schema | EMBEDDED | ALWAYS,MBEDDED,NEVER | 是否初始化数据库:一直、嵌入式、绝不 |
table-prefix | null | 自定义字符串 | 表格前缀 |
schema | jar包里的sql文件路径 | sql文件路径 | sql文件内容 |
job.names | null | 以,分割的字符串 | 需要执行的job名称 |
job.enabled | true | true/false | 是否项目启动时执行job默认执行 |
initializer.enabled | true | true/false | 是否初始化,在2.0.x中已经废除用initialize-schema替代 |
源码分析
job.enabled使用在org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration
的jobLauncherCommandLineRunner
方法中
jobnames的使用在org.springframework.boot.autoconfigure.batch.JobLauncherCommandLineRunner
如果jobNames为空或者无值那么其将执行所有的job,如果不为空那么只执行jobNames中的job
private void executeLocalJobs(JobParameters jobParameters)
throws JobExecutionException {
for (Job job : this.jobs) {
if (StringUtils.hasText(this.jobNames)) {
String[] jobsToRun = this.jobNames.split(",");
if (!PatternMatchUtils.simpleMatch(jobsToRun, job.getName())) {
logger.debug("Skipped job: " + job.getName());
continue;
}
}
execute(job, jobParameters);
}
}