java-如何在Spring Boot中注册和使用jackson AfterburnerModule?

我正在使用SpringBoot 1.5.9,Jackson 2.8和Spring Framework 4.3.13.

我正在尝试注册和使用AfterburnerModel.

根据Spring Boot文档,要配置ObjectMapper,您可以自己定义bean并用@Bean和@Primary对其进行注释.在bean中,您可以注册一个模块.或者,您可以添加类型为Jackson2ObjectMapperBuilder的bean,在其中可以通过添加模块来自定义ObjectMapper.

我尝试了两种方式,并且在序列化期间,杰克逊模块加力燃烧器中没有断点.我的自定义设置已被阅读,但似乎被忽略了.

最佳答案
默认情况下,Spring MVC MappingJackson2HttpMessageConverter将使用Jackson2ObjectMapperBuilder使用默认选项创建自己的ObjectMapper.根据Spring Boot docs 76.3 Customize the Jackson ObjectMapper章节:

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.

因此将模块注册为Bean应该足够了:

@Bean
public AfterburnerModule afterburnerModule() {
  return new AfterburnerModule();
}

可以使用@Configuration类实现更详细的设置,以自定义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());
  }

}

转载注明原文:java-如何在Spring Boot中注册和使用jackson AfterburnerModule? - 代码日志