How to set custom Jackson ObjectMapper with Spring Cloud Netflix Feign
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>
sleepydrmike
Interests: Algorithms, Patterns, Cryptography, and Software Architecture.
Updated on February 19, 2022Comments
-
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 over 6 yearsworked for me simply with
return new JacksonDecoder(customObjectMapper());
-
rios0rios0 about 3 yearsWhat's the dependency? And version? Can you show the pom.xml entry for this?
-
James Wynn almost 3 yearsCan 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 almost 3 yearsgreat improved in my impression, 10ms average improved for 8k qps in production.
-
TuGordoBello over 2 yearsThis works very good. Thanks
-
sleepydrmike about 2 years@TuGordoBello please consider the updated version of this answer.