Modifying spring boot jackson configuration - the right way Posted in coding on 2016-06-26

I had the need make my spring boot application to serialize java.awt.Color objects. If you are familiar with jackson, you might know that this is the perfet usecase for Jackson Mixin Annotations. So I wrote a little SimpleModule which does exactly that.

Now I wanted to add that mixin-module to spring in such a way, that all de-/serialization that occured in my @RequestMappings have the additional capability to de-/serialize them. But something went wrong.

The ugly side of spring

The module was registered, but when serializing, spring wouldn't find the correct mixin. So, my @Configuration was somehow mixed up.

Let's take a look at it:

@Configuration
public class AppConfig {

  @Bean
  public HttpMessageConverters customConverters() {
    return new HttpMessageConverters(
      new CsvHttpMessageConverter());
  }

  @Bean
  ObjectMapper customizeJacksonConfiguration() {
    ObjectMapper om = new ObjectMapper();
    om.registerModule(new GuavaModule());
    JacksonAwtColorModule jacksonAwtColorModule = new JacksonAwtColorModule();
    om.registerModule(jacksonAwtColorModule);
    return om;
  }

}

After fiddling around a bit, it became clear, that two things didn't work as imagined because:

  1. the customConverters() method throws away all previous configuration (which spring boot brings through its auto-configuration)
  2. customizeJacksonConfiguration() also throws defaults of spring over board.

So how to do it better?

Instead of letting spring replace all Message Converters, add @Bean of type Http Message Converter , one bean for each Converter. And provide Module Beans instead of Object Mapper.

The

@Configuration
public class AppConfig {

  @Bean
  public HttpMessageConverter csvConverter() {
        return new CsvHttpMessageConverter();
  }

  @Bean
  Module jacksonGuavaModule() {
    return new GuavaModule();
  }

  @Bean
  Module jacksonAwtModule() {
    return new JacksonAwtColorModule();
  }
}

This works as intended. When the application boots up, spring finds the Module and HtppMessageConverter and adds them to the jackson configuration.


Contact

  • Email
  • github
  • stackoverflow

Information

  • Env: production

Theme

  • krisawzm-blank-bootstrap
2016, .