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
相关产品推荐
相关产品推荐

