2016-03-07 126 views
3

我遇到了一個需要爲第三方API定義一次性@FeignClient的場景。在這個客戶端中,我想使用與我的@Primary不同的自定義Jackson ObjectMapper。我知道可以重寫Spring的假裝配置默認值,但是我不清楚如何僅僅通過這個特定的客戶端來覆蓋ObjectMapper。如何使用Spring雲Netflix Feign設置自定義Jackson ObjectMapper

+0

你有沒有嘗試過了,它不工作? Spring Cloud Feign使用與Spring MVC使用的相同的'HttpMessageConverters'對象。將其配置爲普通的Spring Boot方式應該「正常工作」(以爲我自己並沒有嘗試過)。 http://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#howto-customize-the-jackson-objectmapper – spencergibb

+0

@spencergibb我可以覆蓋ObjectMapper,並且它被所有Spring正確使用MVC控制器和所有Feign客戶端。然而,我需要的是一個特殊的假客戶端,使用默認配置的不同對象映射器。我不知道如何開始做這項工作。 – Newbie

+0

您必須使用之前發佈的doc鏈接創建一個'SpringDecoder' bean,並在那裏混淆它。 – spencergibb

回答

8

根據documentation,您可以爲您的Feign客戶端提供自定義解碼器,如下所示。

假死客戶端接口:

@FeignClient(value = "foo", configuration = FooClientConfig.class) 
public interface FooClient{ 
    //Your mappings 
} 

假死客戶定製配置:

@Configuration 
public class FooClientConfig { 

    @Bean 
    public Decoder feignDecoder() { 
     HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(customObjectMapper()); 
     ObjectFactory<HttpMessageConverters> objectFactory =() -> new HttpMessageConverters(jacksonConverter); 
     return new ResponseEntityDecoder(new SpringDecoder(objectFactory)); 
    } 

    public ObjectMapper customObjectMapper(){ 
     ObjectMapper objectMapper = new ObjectMapper(); 
     //Customize as much as you want 
     return objectMapper; 
    } 
} 
+0

簡單地用'return new JacksonDecoder(customObjectMapper());'' – leveluptor

相關問題