spring batch-JobOperator启动job
2020-04-28 本文已影响0人
刘小刀tina
/**
* @program: demo-spring-batch
* @description: 利用JobOperator启动job 传递参数完成作业
* @author: tina.liu
* @create: 2020-04-28 11:16
**/
@RestController
class JobLauncherController{
@Autowired
private JobOperator jobLauncherDemoJob;
@GetMapping(value = "/job/{msg}")
public String jobRun1(@PathVariable String msg) throws JobParametersInvalidException, JobExecutionAlreadyRunningException, JobRestartException, JobInstanceAlreadyCompleteException, JobInstanceAlreadyExistsException, NoSuchJobException {
jobLauncherDemoJob.start("jobOperatorDemoJob","msg="+msg);
return "job success!";
}
}
/**
* 第二个类
*/
@Configuration
@EnableBatchProcessing
class JobOperatorDemo implements StepExecutionListener , ApplicationContextAware {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
private Map<String, JobParameter> parameters;
@Autowired
private JobLauncher jobLauncher ;
@Autowired
private JobRepository jobRepository;
@Autowired
private JobExplorer jobExplorer ;
@Autowired
private JobRegistry jobRegistry;
private ApplicationContext context;
/**
* 创建Job
* @return
*/
@Bean(value = "jobOperatorDemoJob")
public Job jobOperatorDemoJob(){
return jobBuilderFactory.get("jobOperatorDemoJob")
.start(jobOperatorDemoStep())
.build();
}
/**
*创建step
* @return
*/
@Bean
public Step jobOperatorDemoStep() {
return stepBuilderFactory.get("jobOperatorDemoStep")
.listener(this)
.tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("参数值为:"+parameters.get("msg").getValue());
return RepeatStatus.FINISHED;
}
}).build();
}
@Override
public void beforeStep(StepExecution stepExecution) {
parameters = stepExecution.getJobParameters().getParameters();
}
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
return null;
}
@Bean
public JobOperator jobOperator(){
SimpleJobOperator operator = new SimpleJobOperator();
operator.setJobLauncher(jobLauncher);
operator.setJobParametersConverter(new DefaultJobParametersConverter());
operator.setJobRepository(jobRepository);
operator.setJobExplorer(jobExplorer);
operator.setJobRegistry(jobRegistry);
return operator;
}
@Bean
public JobRegistryBeanPostProcessor jobRegistrar() throws Exception {
JobRegistryBeanPostProcessor postProcessor = new JobRegistryBeanPostProcessor();
postProcessor.setJobRegistry(jobRegistry);
postProcessor.setBeanFactory(context.getAutowireCapableBeanFactory());
postProcessor.afterPropertiesSet();
return postProcessor;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
}