java - Spring Boot 自动配置的 Jackson ObjectMapper 默认情况下不用于 WebFlux WebClient

标签 java spring spring-boot jackson spring-webflux

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

最佳答案

花了相当长的时间调试 Spring WebFlux/Jackson 库代码后,我终于找到了解决问题的提示,查看响应式(Reactive) 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自动注入(inject),因此不需要@Autowired注解。

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

关于java - Spring Boot 自动配置的 Jackson ObjectMapper 默认情况下不用于 WebFlux WebClient,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60335898/

相关文章:

java - Spring Boot Security 忽略 cors 配置

java - "NOT IN"比 <> 慢很多吗?

java - 防御路径遍历攻击的最佳方法是什么?

java - Spring MVC中无法通过ajax调用绑定(bind)ModelMap

Eclipse 没有在多模块 Maven 项目中加载依赖模块

spring-boot - Log4j2 - 无法识别的转换说明符 [xwEx] 从转换模式中的位置 160 开始

java - 为什么我的数组列表没有使用比较器接口(interface)进行排序?

带有特殊字符和数据库的java程序

javascript - 跨平台Ajax上传不起作用

带 Tiles : static webresources not found when deploying as jar 的 Spring Boot