简介
默认情况下启动项目,自动执行Job,如果不想自动运行Job可在yml配置默认不启动Job
创建Job
package com.example.demo.config;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Map;
/**
* @author H__D
* @description
* @date 2021/10/30
*/
@Configuration
// 启用批处理功能
@EnableBatchProcessing
public class JobConfiguration implements StepExecutionListener{
// 注入创建任务的对象
@Autowired
private JobBuilderFactory jobBuilderFactory;
// 注入创建步骤的对象
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Bean(name = "helloworldJob")
public Job helloworldJob() {
System.out.println("ab");
return jobBuilderFactory.get("helloworldJob")
.start(step1())
.build();
}
private Map<String, JobParameter> parameters;
@Bean
public Step step1() {
return stepBuilderFactory.get("step1")
.listener(this)
.tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println(Thread.currentThread().getName() + "------" + "hello world");
System.out.println("传递de参数值为:"+parameters.get("msg").getValue());
// 返回执行完成状态
return RepeatStatus.FINISHED;
}
}).build();
}
/**
* 利用step监听器将参数赋值到step
* @param stepExecution
*/
@Override
public void beforeStep(StepExecution stepExecution) {
parameters = stepExecution.getJobParameters().getParameters();
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}
原创2022/7/23大约 1 分钟