概念
在Job运行时可以以kay=value形式传递参数;
job执行的step,job使用的数据肯定是在step中使用,那我们只需要给step传递数据,如何给step传递参数;
问题?创建Job后,参数在哪里传?怎么给step传参数?
使用监听,使用Step级别的监听来传递参数;
代码
启动类
package com.springbatch._08job_param;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* SpringBatchDemo项目启动类
*
*/
@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchConfig {
public static void main(String[] args) {
SpringApplication.run(SpringBatchConfig.class, args);
}
}
job参数类
package com.springbatch._08job_param;
import org.springframework.batch.core.*;
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;
@Configuration
public class ParamJobConfig implements StepExecutionListener {
//创建 创建job的工厂
@Autowired
private JobBuilderFactory jobBuilderFactory;
//创建 创建step的工厂
@Autowired
private StepBuilderFactory stepBuilderFactory;
Map<String, JobParameter> parameterMap;
@Bean
public Job paramJob() {
return jobBuilderFactory.get("paramJob-01")
.start(paramJobStep())
.build();
}
/**
* 使用监听器获取参数
*
*/
@Bean
public Step paramJobStep() {
return stepBuilderFactory.get("paramJobStep")
.listener(this)
.tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println(parameterMap.get("info"));
return RepeatStatus.FINISHED;
}
})
.build();
}
@Override
public void beforeStep(StepExecution stepExecution) {
parameterMap = stepExecution.getJobParameters().getParameters();
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
}