How to set custom Jackson ObjectMapper with Spring Cloud Netflix Feign

29,624

Solution 1

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;
    }
}

Solution 2

follow @NewBie`s answer, i can give the better one...

  @Bean
  public Decoder feignDecoder() {
    return new JacksonDecoder();
  }

if you want use jackson message converter in feign client, please use JacksonDecoder, because SpringDecoder will increase average latency of feignclient call in production.

    <!-- feign-jackson decoder -->
    <dependency>
      <groupId>io.github.openfeign</groupId>
      <artifactId>feign-jackson</artifactId>
      <version>10.1.0</version>
    </dependency>
Share:
29,624
sleepydrmike
Author by

sleepydrmike

Interests: Algorithms, Patterns, Cryptography, and Software Architecture.

Updated on February 19, 2022

Comments

  • sleepydrmike
    sleepydrmike about 2 years

    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.

  • leveluptor
    leveluptor over 6 years
    worked for me simply with return new JacksonDecoder(customObjectMapper());
  • rios0rios0
    rios0rios0 about 3 years
    What's the dependency? And version? Can you show the pom.xml entry for this?
  • James Wynn
    James Wynn almost 3 years
    Can you quantify the increase in latency in either percentage or ms or something? I'd like a reference point for how much difference this makes. Looks clean though.
  • suiwenfeng
    suiwenfeng almost 3 years
    great improved in my impression, 10ms average improved for 8k qps in production.
  • TuGordoBello
    TuGordoBello over 2 years
    This works very good. Thanks
  • sleepydrmike
    sleepydrmike about 2 years
    @TuGordoBello please consider the updated version of this answer.