批处理基础设施配置

如前所述,Spring Batch 依赖于许多基础设施 bean 来操作作业和步骤,包括 JobOperatorJobRepository。虽然可以手动定义这些 bean,但使用 @EnableBatchProcessing 注解或 DefaultBatchConfiguration 类来提供基本配置要容易得多。

默认情况下,Spring Batch 将提供一个无资源批处理基础设施配置,它基于 ResourcelessJobRepository 实现。如果要使用数据库支持的作业仓库,可以使用 @EnableJdbcJobRepository / @EnableMongoJobRepository 注解或等效的类 JdbcDefaultBatchConfiguration / MongoDefaultBatchConfiguration,如配置 JobRepository 部分所述。

基于注解的配置

@EnableBatchProcessing 注解的工作方式类似于 Spring 系列中的其他 @Enable* 注解。在这种情况下,@EnableBatchProcessing 为构建批处理作业提供了基本配置。在此基本配置中,除了许多可自动装配的 bean 外,还会创建 StepScopeJobScope 实例

  • 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 注解。一旦您有一个带有该注解的类,您就拥有了前面描述的所有配置。

编程配置

与基于注解的配置类似,通过 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 使用编程方式,但不能同时使用这两种方式。
© . This site is unofficial and not affiliated with VMware.