跳到主要内容
版本:6.0.2

批处理基础设施配置

DeepSeek V3 中英对照 Batch infrastructure Configuration

如前所述,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 的配置。

important

@EnableBatchProcessing 不应DefaultBatchConfiguration 同时使用。您应该选择通过 @EnableBatchProcessing 以声明式方式配置 Spring Batch,或者选择通过扩展 DefaultBatchConfiguration 以编程式方式进行配置,但不应同时使用这两种方式。