# Spring Batch 5 不建議使用 EnableBatchProcessing

因為最近要處理 Data pipeline 的問題, 重新溫習了 Spring batch 配置, 其中一個地雷是 `@EnableBatchProcessing` 的 annotation 宣告, 導致了 Batch 作業相關 DDL 沒有被建立.

在 Spring boot 3.0 的 [Migration Guide](https://github.com/spring-projects/spring-boot/wiki/Spring-Boot-3.0-Migration-Guide#spring-batch-changes) 裡面特別注記了這段, 建議不應該再使用 `@EnableBatchProcessing`.

> #### **@ EnableBatchProcessing is now discouraged**
> 
> Previously, `@EnableBatchProcessing` could be used to enable Spring Boot’s auto-configuration of Spring Batch. It is no longer required and should be removed from applications that want to use Boot’s auto-configuration. A bean that is annotated with `@EnableBatchProcessing` or that extends Batch’s `DefaultBatchConfiguration` can now be defined to tell the auto-configuration to back off, allowing the application to take complete control of how Batch is configured.

## 實際測試如下

### BatchAutoConfiguration 有成功配置

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1748862466678/942e4c52-bb94-492a-93c0-6294354bbc82.png align="center")

## BatchAutoConfiguration 沒有配置

這邊 log 描述, 在第一個條件因為配置了 EnableBatchProcessing 導致 DefaultBatchConfiguration 失效.

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1748862991990/0c80b80e-d8d5-429f-aab3-920165290841.png align="center")

## 產生 Batch DDL 的需求考量

1. 若專案有設定 \`spring.jpa.hibernate.ddl-auto: update\` 或是其他行為, 應該要注意一下 DDL 是否彼此有互相影響, 確保 `dataSource` 和 `transactionManager` 使用到的到底是什麼, 開啟 debug 觀察看看
    
2. 考慮預設的 Batch DDL 是否有其價值? 預設的好處就是開箱即用, 然而其實自己設計 DDL 來記錄 Job 成功或失敗, 也沒有不好, 格式反而可以自己配置的更明確, 抓到更多資料處理細節.
    
3. Batch 作業通常是一個長時間的作業流程, 有些時候獨立成一個 Batch 服務, 解耦架構或許是一個方向.
    
4. 要不要配置 `@EnableBatchProcessing`? 看文件是說有支援 [Micrometer’s trace](https://docs.spring.io/spring-batch/reference/tracing.html#page-title) 的機制, 但需要配置好 `dataSource` 和 `transactionManager` 相關依賴, 我覺得可以做取捨.
    

## Ref

* StackOverflow - [https://stackoverflow.com/questions/49583662/adding-enablebatchprocessing-causes-transactionrequiredexception-errors](https://stackoverflow.com/questions/49583662/adding-enablebatchprocessing-causes-transactionrequiredexception-errors)
    
* Github Issues - [https://github.com/spring-projects/spring-batch/issues/4336#issuecomment-1485292860](https://github.com/spring-projects/spring-batch/issues/4336#issuecomment-1485292860)
    
* HowtodoInJava - [https://howtodoinjava.com/spring-batch/spring-boot-batch-tutorial-example/#22-enabling-batch-processing](https://howtodoinjava.com/spring-batch/spring-boot-batch-tutorial-example/#22-enabling-batch-processing)
