Reputation: 163
I use both Kafka and @RestController in my Spring Boot project. And I need to declare two different configs of ObjectMapper (Jackson) for @RestController and my Kafka classes. One of them which is for Kafka looks like this:
@Bean
@Primary
public ObjectMapper newJacksonJsonProvider() {
SimpleModule module = new SimpleModule();
module.addDeserializer(ZonedDateTime.class, new ZonedDateTimeCustomDeserializer());
return new ObjectMapper()
.configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true)
.setPropertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE)
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)
.registerModule(new ParameterNamesModule())
.registerModule(module);
}
for the rest controllers I need a basic one. Or just a one which won't be conflicting with the above one.
Also, I use a multi-module project. So, maybe there is a possibility how to separate it, so there will be no collision.
Upvotes: 0
Views: 949
Reputation: 161
So if you really just need two instances of ObjectMapper, then I would suggest you should actually make the other one @Primary, and inject the custom one wherever you specifically need it using the @Qualifier annotation like so:
@Bean(name = "defaultObjectMapper")
@Primary
ObjectMapper defaultObjectMapper() {
return new ObjectMapper();
}
@Bean(name = "customizedObjectMapper")
ObjectMapper customizedObjectMapper() {
var objectMapper = new ObjectMapper();
//customization goes here
return objectMapper;
}
Then you can autowire the customized one where you need it like so:
//constructor for a service that requires the custom ObjectMapper
ServiceUsingAutowiredObjectMapper(@Qualifier("customizedObjectMapper") ObjectMapper objectMapper) {
//code goes here
}
However, since you specifically mentioned Kafka I feel like you probably could rather configure JsonSerializer/Deserializer for Kafka specifically without exposing that customized ObjectMapper as a bean. (see spring kafka docs for details on using custom serializer/deserializer for Kafka)
Upvotes: 1