Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 637
dasPing Avatar asked Mar 23 '18 16:03

dasPing


1 Answers

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

}
like image 80
Karol Dowbecki Avatar answered Nov 11 '22 19:11

Karol Dowbecki