2016-03-07 113 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

相关问题