How can I register and use the jackson AfterburnerModule in Spring Boot?

dasPing picture dasPing · Mar 23, 2018 · Viewed 9.5k times · Source

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.

Answer

Karol Dowbecki picture Karol Dowbecki · Mar 23, 2018

By default Spring MVC MappingJackson2HttpMessageConverter will create it's 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());
  }

}