Search code examples
spring-bootjacksonobjectmapper

ObjectMapper in RestClient not picking up configuration properties


In my Spring Boot service, I'm using RestClient to perform REST calls. I want to ignore null values in request bodies so I set up

spring:
  jackson:
    default-property-inclusion: "non_null"

in my application.yml. However, the config is not respected for some reason in the RestClient's ObjectMapper. On the other hand, when I inject the Spring auto-configured ObjectMapper into my test class (annotated with @SpringBootTest) I see the mapper configured as expected. What could be the reason for RestClient picking up a different ObjectMapper than the one configured by Spring Boot?

Couple of notes:

  • I'm not configuring ObjectMapper in any other way than via application.yml
  • I'm doing RestClient.create() to set up the RestClient
  • I don't use @EnableWebMvc (the usual suspect in similar SO questions)

Solution

  • You need to, at least, use RestClient.create(restTemplate). Your RestTemplate needs to be configured with the ObjectMapper you need.

    When you use RestClient.create() it has no way of picking up spring-configured mapper, how could it? It's regular java object creation.

    There are some other options, for example:

    RestClient.builder()
      .messageConverters(in -> {
        MappingJackson2HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter();
        messageConverter.setPrettyPrint(false);
        messageConverter.setObjectMapper(objectMapper);
        in.add(jacksonConverter);
      })
    .build();