Spring Batch 5迁移:如何在Spring Boot默认配置下启用Jackson序列化器?
在Spring Boot 3默认配置下启用Spring Batch 5的Jackson序列化器
不用通过@EnableBatchProcessing或继承DefaultBatchConfiguration接管配置,Spring Boot 3的Spring Batch自动配置支持通过注册特定Bean来替换序列化器,完全兼容默认的自动配置逻辑,也不会影响--spring.batch.job.name参数的使用。具体步骤如下:
1. 确保Jackson依赖存在
Spring Boot 3的spring-boot-starter-batch默认不包含Jackson依赖,需要确保spring-boot-starter-json在类路径中:
Maven依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-json</artifactId> </dependency>
Gradle依赖
implementation 'org.springframework.boot:spring-boot-starter-json'
2. 注册Jackson序列化器Bean
Spring Batch 5会自动识别容器中的ExecutionContextSerializer类型Bean,并将其用于JobRepository的序列化/反序列化。直接创建Jackson2ExecutionContextStringSerializer的Bean即可:
import org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class BatchJacksonConfiguration { @Bean public Jackson2ExecutionContextStringSerializer executionContextSerializer() { Jackson2ExecutionContextStringSerializer serializer = new Jackson2ExecutionContextStringSerializer(); // 若需要适配历史数据的序列化规则,可在这里自定义ObjectMapper // serializer.setObjectMapper(customObjectMapper()); return serializer; } }
3. 适配历史数据的自定义配置
如果历史数据使用的Jackson配置与当前默认配置不一致(比如日期格式、序列化特性),可以自定义ObjectMapper并注入到序列化器中:
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class BatchJacksonConfiguration { @Bean public ObjectMapper batchObjectMapper() { ObjectMapper objectMapper = new ObjectMapper(); // 示例:启用时间戳格式序列化(适配旧版配置) objectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); // 注册Java 8时间模块 objectMapper.registerModule(new JavaTimeModule()); // 添加其他历史数据兼容配置 return objectMapper; } @Bean public Jackson2ExecutionContextStringSerializer executionContextSerializer(ObjectMapper batchObjectMapper) { Jackson2ExecutionContextStringSerializer serializer = new Jackson2ExecutionContextStringSerializer(); serializer.setObjectMapper(batchObjectMapper); return serializer; } }
4. 验证配置生效
启动应用后,查看日志中是否包含类似如下内容,确认序列化器已被正确加载:
Using ExecutionContextSerializer: org.springframework.batch.core.repository.dao.Jackson2ExecutionContextStringSerializer
运行作业测试,验证历史数据的反序列化是否正常。
内容的提问来源于stack exchange,提问作者Tyler Hartwig
相关产品推荐
相关产品推荐

