【问题标题】:Spring Boot auto-configured Jackson ObjectMapper not used for WebFlux WebClient by defaultSpring Boot 自动配置的 Jackson ObjectMapper 默认不用于 WebFlux WebClient
【发布时间】:2020-06-05 17:18:08
【问题描述】:

在我的 Spring Boot 应用程序中,我使用响应式 WebFlux WebClient 从 SSE(服务器发送事件)端点检索流式 JSON 数据。按照official docs 的建议,通过在Spring Boot 中设置spring.jackson.deserialization.read-date-timestamps-as-nanoseconds=false 之类的配置选项来修改默认的自动配置Jackson ObjectMapper 行为对WebFlux WebClient 没有影响。我还尝试了SO thread 中列出的其他建议,例如为 WebFlux 配置创建自定义 bean,但它们没有帮助,配置仍然没有被拾取。

【问题讨论】:

    标签: java spring spring-boot jackson spring-webflux


    【解决方案1】:

    在调试 Spring WebFlux / Jackson 库代码相当长的一段时间后,我终于能够通过查看响应式 WebFlux WebClient docs 找到解决问题的提示。使 WebClient 使用默认的自动配置 Jackson ObjectMapper 需要一些自定义管道。解决方案是在创建 WebClient 的新实例时配置用于处理服务器发送事件的默认解码器。下面是示例代码:

    @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是Spring自动注入的,所以不需要@Autowired注解。

    如果可以在官方文档中以某种方式更明确地说明这一点,那肯定会有所帮助。希望这个答案对面临类似问题的人有用!

    【讨论】:

    猜你喜欢
    • 2017-08-28
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 2017-05-01
    • 2019-06-07
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多