How can I register and use the jackson AfterburnerModule in Spring Boot?
By default Spring MVC MappingJackson2HttpMessageConverter
will create its own ObjectMapper
with default options using Jackson2ObjectMapperBuilder
. As per Spring Boot docs 76.3 Customize the Jackson ObjectMapper chapter:
Any beans of type com.fasterxml.jackson.databind.Module are automatically registered with the auto-configured Jackson2ObjectMapperBuilder and are applied to any ObjectMapper instances that it creates. This provides a global mechanism for contributing custom modules when you add new features to your application.
so it should be enough to register your module as a bean:
@Bean
public AfterburnerModule afterburnerModule() {
return new AfterburnerModule();
}
A more detailed setup can be achieved with @Configuration
class to customize the MappingJackson2HttpMessageConverter
:
@Configuration
public class MyMvcConf extends WebMvcConfigurationSupport {
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(myConverter());
addDefaultHttpMessageConverters(converters);
}
@Bean
public MappingJackson2HttpMessageConverter myConverter() {
return new MappingJackson2HttpMessageConverter(myObjectMapper())
}
@Bean
public ObjectMapper myObjectMapper() {
return new ObjectMapper().registerModule(new AfterburnerModule());
}
}
Comments
-
dasPing almost 2 years
I am using SpringBoot 1.5.9., Jackson 2.8 and Spring Framework 4.3.13.
I am trying to register and use the AfterburnerModel.
According to the Spring Boot documentation, to configure the ObjectMapper you can either define the bean yourself and annotate it with @Bean and @Primary. In the bean you can register a module. Or you can add a bean of type Jackson2ObjectMapperBuilder where you can customize the ObjectMapper, by adding a module.
I have tried both ways, and during serialization none of my breakpoints in jackson-module-afterburner fire. My customizations are being read, but seem to be being ignored.
-
dasPing about 6 yearsThanks, I already tried that. As I mentioned in the original post the bean is being read. The problem I suspect is that other ObjectMappers are being created and used for example by AllEncompassingFormHttpMessageConverter
-
Karol Dowbecki about 6 yearsUpdated the answer, most likely your new
ObjectMapper
is not configured as part of the Spring MVC converters. -
dasPing about 6 yearsInteresting, but the same problem. Here is the current stacktrace where the defualt objectmapper is being created: ObjectMapper.<init>() line: JsonMapperConfigurator.getDefaultMapper() ResteasyJackson2Provider(ProviderBase).locateMapper(Class<?>, MediaType)
-
Karol Dowbecki about 6 yearsYou seem to be using JAX-RS with RESTEasy which is not mentioned in your question. Check stackoverflow.com/a/29019303/1602555.
-
Josh C. over 5 yearsDo you notice a performance improvement after adding afterburner? Do you know if this works with spring kafka's jsonserializer?