新建一个Spring boot工程,项目管理工具为maven。
1、下面新建一个Batch的配置类
package com.lzj.spring.batch;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
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;
@Configuration
public class BatchConfig {
/*自动注入Step的工厂类*/
@Autowired
private StepBuilderFactory stepBuilderFactory;
/*自动注入Job的工厂类*/
@Autowired
private JobBuilderFactory jobBuilderFactory;
private static int i = 0;
/*创建一个Step,在Step中处理批处理逻辑*/
@Bean
public Step step1(){
Step step = stepBuilderFactory.get("step1").tasklet((contribution, chunkContext) -> {
System.out.println("step1 begin process...");
System.out.println("step1 is processing...");
System.out.println("step1 end process...");
/*批处理结束后,返回FINISHED状态*/
return RepeatStatus.FINISHED;
}).build();
return step;
}
/*创建一个Job,一个Job中可以包含一个或多个Step,相当于一份工作分多步来执行*/
@Bean
public Job job1(){
Job job = jobBuilderFactory.get("job1").start(step1()).build();
return job;
}
}
2、启动工程
spring boot工程的启动类如下:
package com.lzj.spring;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/*在启动的时候一定要加入@EnableBatchProcessing 注解,用来启动Spring batch的功能,否则Batch的功能无效*/
@EnableBatchProcessing
@SpringBootApplication
public class BatchDemoApp {
public static void main(String[] args) {
SpringApplication app = new SpringApplication(BatchDemoApp.class);
app.run(args);
}
}
启动启动类,将自动执行批处理功能,输出日志如下:
……省略日志
job1 begin process...
……省略日志
step1 begin process...
step1 is processing...
step1 end process...
……省略日志