代码之家  ›  专栏  ›  技术社区  ›  Fletch

设置WebClient.Builder.ExchangeStrategies(),而不丢失Spring Jackson配置

  •  1
  • Fletch  · 技术社区  · 6 年前

    我使用以下代码(从 this answer )要配置要登录到WebClient请求的头,请执行以下操作:

    ExchangeStrategies exchangeStrategies = ExchangeStrategies.withDefaults();
    exchangeStrategies
        .messageWriters().stream()
        .filter(LoggingCodecSupport.class::isInstance)
        .forEach(writer -> ((LoggingCodecSupport)writer).setEnableLoggingRequestDetails(true));
    
    client = WebClient.builder()
        .exchangeStrategies(exchangeStrategies)
    

    这样可以,但会导致我的杰克逊配置丢失。在application.properties中,我有:

    spring.jackson.default-property-inclusion=non-null
    spring.jackson.deserialization.accept-empty-string-as-null-object=true
    

    被上述代码覆盖。这是我的解决方法:

      @Autowired ObjectMapper objectMapper;
    
      @Bean
      WebClientCustomizer webClientCustomizer() {
        return (WebClient.Builder builder) -> {
          builder
              .exchangeStrategies(createExchangeStrategiesWhichLogHeaders())
        };
      }
    
      private ExchangeStrategies createExchangeStrategiesWhichLogHeaders() {
        ExchangeStrategies exchangeStrategies =
            ExchangeStrategies.builder()
                .codecs(
                    clientDefaultCodecsConfigurer -> {
                      clientDefaultCodecsConfigurer
                          .defaultCodecs()
                          .jackson2JsonEncoder(
                              new Jackson2JsonEncoder(objectMapper, MediaType.APPLICATION_JSON));
                      clientDefaultCodecsConfigurer
                          .defaultCodecs()
                          .jackson2JsonDecoder(
                              new Jackson2JsonDecoder(objectMapper, MediaType.APPLICATION_JSON));
                    })
                .build();
    
        exchangeStrategies
            .messageWriters()
            .stream()
            .filter(LoggingCodecSupport.class::isInstance)
            .forEach(writer -> ((LoggingCodecSupport) writer).setEnableLoggingRequestDetails(true));
    
        return exchangeStrategies;
      }
    

    这是可行的,但感觉有点奇怪。问题是:我需要像这样包含Jackson/Objectmapper配置吗,还是有一种更简单的方法来避免覆盖Spring Objectmapper配置?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Brian Clozel    6 年前

    从SpringBoot2.1.0开始,您可以通过启用以下属性来实现这一点:

    spring.http.log-request-details=true
    

    如果您使用的是以前的Spring引导版本,那么您应该能够在不覆盖或重新构建整个配置的情况下自定义此版本,如下所示:

    @Configuration
    static class LoggingCodecConfig {
    
        @Bean
        @Order(0)
        public CodecCustomizer loggingCodecCustomizer() {
            return (configurer) -> configurer.defaultCodecs()
                    .enableLoggingRequestDetails(true);
        }
    
    }