Spring Boot集成Spring Batch快速入门Demo
import org.springframework.batch.core.Job;
import org.springframework.batch.core.Step;
import org.springframework.batch.core.StepContribution;
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.launch.JobLauncher;
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.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
@EnableBatchProcessing
public class SpringBatchQuickstartApplication {
@Autowired
private JobBuilderFactory jobs;
@Autowired
private StepBuilderFactory steps;
@Autowired
private JobLauncher jobLauncher;
// 创建Tasklet作为步骤中的操作
public Tasklet helloWorldTasklet() {
return (StepContribution contribution, ChunkContext chunkContext) -> {
System.out.println("Hello World!");
return RepeatStatus.FINISHED;
};
}
// 定义一个简单的步骤
public Step helloWorldStep() {
return steps.get("helloWorldStep")
.tasklet(helloWorldTasklet())
.build();
}
// 定义一个简单的作业,并将步骤包含进去
public Job helloWorldJob() {
return jobs.get("helloWorldJob")
.start(helloWorldStep())
.build();
}
// 应用启动时运行作业
public void runJob(ApplicationContext context) throws Exception {
Job job = context.getBean(Job.class);
jobLauncher.run(job, new JobParameters());
}
public static void main(String[] args) {
SpringApplication.run(SpringBatchQuickstartApplication.class, args);
}
}
这段代码展示了如何在Spring Boot应用程序中创建一个简单的Spring Batch作业,并在启动时运行它。代码中定义了一个Tasklet,一个步骤,以及一个作业,并且展示了如何使用@EnableBatchProcessing
注解来启用Spring Batch的自动配置。最后,在主方法中,我们调用SpringApplication.run()
来启动Spri
评论已关闭