批處理基礎設施配置

如前所述,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.