springspring-mvcspring-cloudfeignspring-cloud-netflix

How to set custom Jackson ObjectMapper with Spring Cloud Netflix Feign


I'm running into a scenario where I need to define a one-off @FeignClient for a third party API. In this client I'd like to use a custom Jackson ObjectMapper that differs from my @Primary one. I know it is possible to override spring's feign configuration defaults however it is not clear to me how to simply override the ObjectMapper just by this specific client.


Solution

  • Per the documentation, you can provide a custom decoder for your Feign client as shown below.

    Feign Client Interface:

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

    Feign Client Custom Configuration:

    @Configuration
    public class FooClientConfig {
    
        @Bean
        public Decoder feignDecoder() {
            HttpMessageConverter jacksonConverter = new MappingJackson2HttpMessageConverter(customObjectMapper());
    
            HttpMessageConverters httpMessageConverters = new HttpMessageConverters(jacksonConverter);
            ObjectFactory<HttpMessageConverters> objectFactory = () -> httpMessageConverters;
    
    
            return new ResponseEntityDecoder(new SpringDecoder(objectFactory));
        }
    
        public ObjectMapper customObjectMapper(){
            ObjectMapper objectMapper = new ObjectMapper();
            //Customize as much as you want
            return objectMapper;
        }
    }