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

Spring Boot中RestClient的ObjectMapper未读取Jackson配置问题排查

问题原因

直接调用RestClient.create()创建的是脱离Spring容器管理的独立实例,它默认使用Jackson原生的ObjectMapper,不会自动加载Spring Boot通过application.yml配置的Jackson参数。而测试类中注入的ObjectMapper是Spring Boot自动配置并纳入容器管理的实例,自然会遵循spring.jackson下的配置规则。

解决办法

有两种常用方案可以让RestClient使用Spring配置好的ObjectMapper:

方案一:通过Spring管理的RestClient.Builder构建实例

不要直接调用RestClient.create(),改为注入Spring容器提供的RestClient.Builder来构建RestClient,它会自动关联容器中配置好的ObjectMapper:

@Service
public class YourService {
    private final RestClient restClient;

    // 注入RestClient.Builder
    public YourService(RestClient.Builder restClientBuilder) {
        this.restClient = restClientBuilder
                .baseUrl("https://your-api-url.com")
                .build();
    }
}

方案二:手动指定Spring的ObjectMapper给RestClient

如果需要自定义RestClient的创建逻辑,可以手动获取Spring容器中的ObjectMapper,替换RestClient默认的消息转换器:

@Service
public class YourService {
    private final RestClient restClient;

    public YourService(ObjectMapper objectMapper) {
        this.restClient = RestClient.builder()
                .baseUrl("https://your-api-url.com")
                .messageConverters(converters -> {
                    // 找到MappingJackson2HttpMessageConverter并替换其ObjectMapper
                    converters.stream()
                            .filter(converter -> converter instanceof MappingJackson2HttpMessageConverter)
                            .forEach(converter -> ((MappingJackson2HttpMessageConverter) converter).setObjectMapper(objectMapper));
                })
                .build();
    }
}

内容的提问来源于stack exchange,提问作者David Kubecka

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:11:02