Home » Java » java – Spring Boot auto-configured Jackson ObjectMapper not used for WebFlux WebClient by default-Exceptionshub

java – Spring Boot auto-configured Jackson ObjectMapper not used for WebFlux WebClient by default-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

In my Spring Boot application I’m making use of the reactive WebFlux WebClient to retrieve streaming JSON data from an SSE (Server-Sent Events) endpoint. Modifying the default auto-configured Jackson ObjectMapper behavior by setting config options in Spring Boot like spring.jackson.deserialization.read-date-timestamps-as-nanoseconds=false as suggested by the official docs has no effect on the WebFlux WebClient. I also tried other suggestions outlined in this SO thread like creating custom beans for WebFlux configuration but they did not help, the config is still not being picked up.

How to&Answers:

After quite some time spent debugging Spring WebFlux / Jackson library code, I was able to finally find a hint to solve the issue looking at the reactive WebFlux WebClient docs. There is some custom plumbing required to make WebClient use the default auto-configured Jackson ObjectMapper. The solution is to configure the default decoder used for processing Server-Sent Events when creating new instance of the WebClient. Here is the sample code:

@Component
public class MarketDataFetcher implements CommandLineRunner {

    // ...

    private final WebClient webClient;

    public MarketDataFetcher(ObjectMapper objectMapper) {
        webClient = createWebClient(objectMapper);
    }

    private WebClient createWebClient(ObjectMapper objectMapper) {
        return WebClient.builder()
                .codecs(configurer -> configurer.defaultCodecs()
                        .serverSentEventDecoder(new Jackson2JsonDecoder(objectMapper)))
                .baseUrl(BASE_URL)
                .build();
    }
}

ObjectMapper is automatically injected by Spring, so no @Autowired annotation is needed.

It would certainly help if this could be made more explicit in the official documentation somehow. Hope this answer can be useful for someone facing similar issue!