You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 2.7.4中LocalDate序列化报错求助(含已尝试方案)

解决方案

问题根源

QueueMessagingTemplate 默认使用的 MappingJackson2MessageConverter 并没有复用你自定义的 @Primary ObjectMapper,而是会创建独立的实例,导致你添加的 JavaTimeModule 未生效,进而无法序列化 LocalDate 类型。

步骤1:确保依赖完整性

尽管 Spring Boot 2.7.x 的 spring-boot-starter-json 已内置 jackson-datatype-jsr310,但为避免依赖缺失,显式添加该依赖:

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
</dependency>

步骤2:配置自定义消息转换器

创建配置类,让 QueueMessagingTemplate 使用你的自定义 ObjectMapper:

import com.fasterxml.jackson.databind.ObjectMapper
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.messaging.converter.MappingJackson2MessageConverter
import org.springframework.messaging.converter.MessageConverter

@Configuration
class MessagingConverterConfig(
    private val objectMapper: ObjectMapper
) {

    @Bean
    fun jacksonMessageConverter(): MessageConverter {
        val converter = MappingJackson2MessageConverter()
        converter.objectMapper = objectMapper
        converter.targetType = org.springframework.messaging.converter.MessageType.TEXT
        return converter
    }
}

步骤3:优化 ObjectMapper 配置

改用 Spring Boot 提供的 Jackson2ObjectMapperBuilder 构建实例,确保同时加载 KotlinModule 和 JavaTimeModule:

import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.SerializationFeature
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
import com.fasterxml.jackson.module.kotlin.KotlinModule
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Primary
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder

@Configuration
class JacksonModuleConfig {

    @Bean
    @Primary
    fun objectMapper(builder: Jackson2ObjectMapperBuilder): ObjectMapper {
        return builder
            .modules(KotlinModule(), JavaTimeModule())
            .featuresToDisable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
            .build()
    }
}

步骤4:验证模板与转换器绑定

如果你的 QueueMessagingTemplate 是自动注入的,Spring 会自动检测并使用上述自定义转换器。若为手动创建模板,需显式注入转换器:

@Bean
fun queueMessagingTemplate(
    connectionFactory: ConnectionFactory,
    messageConverter: MessageConverter
): QueueMessagingTemplate {
    val template = QueueMessagingTemplate(connectionFactory)
    template.messageConverter = messageConverter
    return template
}

完成以上配置后,QueueMessagingTemplate 在调用 convertAndSend 时会使用带有 JavaTimeModule 的 ObjectMapper,即可正确序列化 LocalDate 类型。

内容的提问来源于stack exchange,提问作者Sergio Luigi Alves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 07:30:55