我正在使用以下代码来配置要在WebClient请求上记录的标头:
ExchangeStrategies exchangeStrategies = ExchangeStrategies.withDefaults(); exchangeStrategies .messageWriters().stream() .filter(LoggingCodecSupport.class::isInstance) .forEach(writer -> ((LoggingCodecSupport)writer).setEnableLoggingRequestDetails(true)); client = WebClient.builder() .exchangeStrategies(exchangeStrategies)
这可行,但是会导致我的Jackson配置丢失。在我的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配置被覆盖?
从Spring Boot 2.1.0开始,您可以通过启用以下属性来实现此目的:
spring.http.log-request-details=true
如果您使用的是先前的Spring Boot版本,则应该能够自定义此版本,而不会覆盖或重建整个配置,如下所示:
@Configuration static class LoggingCodecConfig { @Bean @Order(0) public CodecCustomizer loggingCodecCustomizer() { return (configurer) -> configurer.defaultCodecs() .enableLoggingRequestDetails(true); } }