当前版本仍在开发中,尚不被视为稳定版本。最新稳定版请使用 Spring Batch 文档 6.0.2!

批处理基础设施配置

如前所述,Spring Batch 依赖一组基础设施 bean 来驱动作业和步骤的运行, 其中包括 JobOperatorJobRepository。虽然你也可以手动定义这些 bean, 但使用 @EnableBatchProcessing 注解或 DefaultBatchConfiguration 类来提供基础配置会更简单。

默认情况下,Spring Batch 会提供一个无资源依赖的批处理基础设施配置,其底层基于 ResourcelessJobRepository 实现。如果你希望使用由数据库支撑的作业仓库, 可以使用 @EnableJdbcJobRepository / @EnableMongoJobRepository 注解, 或者使用等价的 JdbcDefaultBatchConfiguration / MongoDefaultBatchConfiguration 类, 具体可参见配置 JobRepository一节。

基于注解的配置

@EnableBatchProcessing 注解的工作方式与 Spring 体系中的其他 @Enable* 注解类似。 在这里,@EnableBatchProcessing 为构建批处理作业提供了一套基础配置。 在这套基础配置中,除了会创建 StepScopeJobScope 实例外, 还会提供一组可供自动注入的 bean:

  • JobRepository:名为 jobRepository 的 bean

  • JobOperator:名为 jobOperator 的 bean

下面是一个在 Java 配置类中使用 @EnableBatchProcessing 注解的示例:

@Configuration
@EnableBatchProcessing
public class MyJobConfiguration {

	@Bean
	public Job job(JobRepository jobRepository) {
		return new JobBuilder("myJob", jobRepository)
				//define job flow as needed
				.build();
	}

}

你可以通过 @EnableBatchProcessing 注解的属性,对任意基础设施 bean 的配置进行定制。

只需要有一个配置类标注 @EnableBatchProcessing。一旦存在这样一个类, 前面提到的那些配置就都会具备。

编程式配置

与基于注解的配置类似,Spring Batch 还通过 DefaultBatchConfiguration 类提供了 一种以编程方式配置基础设施 bean 的手段。这个类会提供与 @EnableBatchProcessing 相同的那些 bean,并且可以作为配置批处理作业的基类来使用。下面的代码片段展示了一个典型用法:

@Configuration
class MyJobConfiguration extends DefaultBatchConfiguration {

	@Bean
	public Job job(JobRepository jobRepository) {
		return new JobBuilder("myJob", jobRepository)
				// define job flow as needed
				.build();
	}

}

你可以通过覆写所需的 setter 方法,来自定义任意基础设施 bean 的配置。

@EnableBatchProcessing 不应DefaultBatchConfiguration 同时使用。 你应当二选一:要么通过 @EnableBatchProcessing 以声明式方式配置 Spring Batch, 要么通过继承 DefaultBatchConfiguration 以编程式方式进行配置, 但不要在同一时间混用这两种方式。