需要在配置文件中设置
spring.batch.job.enabled = false
@Configuration
@EnableBatchProcessing
public class JobDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private JobLauncher jobLauncher;
@Autowired
private JobOperator jobOperator;
@Autowired
private JobRepository jobRepository;
@Autowired
private JobRegistry jobRegistry;
@Autowired
private JobExplorer jobExplorer;
@Autowired
private ApplicationContext context;//或者implements ApplicationContextAware 通过构造注入
@Bean("demo")
public Job jobDemo() {
return jobBuilderFactory.get("demo").start(step1()).on("COMPLETED")
.to(step2()).from(step2()).on("COMPLETED")
.to(step3()).from(step3()).end()
.build();
//return jobBuilderFactory.get("demo").start(step1()).next(step2()).next(step3()).build();
}
public Step step3() {
return stepBuilderFactory.get("step3").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("================step3==============");
return RepeatStatus.FINISHED;
}
}).build();
}
public Step step2() {
return stepBuilderFactory.get("step2").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("================step2==============");
return RepeatStatus.FINISHED;
}
}).build();
}
public Step step1() {
return stepBuilderFactory.get("step1").tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) throws Exception {
System.out.println("================step1==============");
return RepeatStatus.FINISHED;
}
}).build();
}
public void lunch() throws Exception {
JobParameters parameters = new JobParametersBuilder()
.addString("", "")//添加参数
.toJobParameters();
jobLauncher.run(jobDemo(), parameters);//启动任务
jobOperator.start("jobDemo", "meg=" + "");//jobOperator需要自己定义
//自定义的jobOperator需要自己定义
/*SimpleJobOperator jobOperator = new SimpleJobOperator();
jobOperator.setJobLauncher(jobLauncher);
jobOperator.setJobParametersConverter(new DefaultJobParametersConverter());//参数转换器
jobOperator.setJobRepository(jobRepository);//jobRepository持久化
jobOperator.setJobExplorer(jobExplorer);//jobExplorer获取和任务相关的信息
jobOperator.setJobRegistry(jobRegistry);//注册,需要创建,根据job名称获取job对象
*/
}
//jobRegistry
@Bean
public JobRegistryBeanPostProcessor registryBeanPostProcessor() throws Exception {
JobRegistryBeanPostProcessor registryBeanPostProcessor = new JobRegistryBeanPostProcessor();
registryBeanPostProcessor.setJobRegistry(jobRegistry);
registryBeanPostProcessor.setBeanFactory(context.getAutowireCapableBeanFactory());
registryBeanPostProcessor.afterPropertiesSet();
return registryBeanPostProcessor;
}
}