简体   繁体   中英

Spring Boot and ObjectMapper configuration

Using Spring Boot 1.2.2 to create an Spring MVC application. I am also using Spring HATEOAS.

The issue I am having is that my configured ObjectMapper is used properly when my controller methods return a List<> , but a different ObjectMapper is being used when I return my Resource classes (eg MyClass extends ResourceSupport )

It's a more than a little frustrating to try to configure Jackson's ObjectMapper . I have followed the documentation and added my own ObjectMapper @Bean to a @Configuration class and annotated it with @Primary , and that one is being used when serializing List<> .

Setting a breakpoint in the ObjectMapper constructor breakpoint reveals that the constructor is called about 20 times. I made a poor summary of each scenario:

  1. My configuration class ( @Bean annotated with @Primary )
  2. halObjectMapper
  3. WebMvcConfigurationSupport->requestMappingHandlerAdapter()->AllEncompassingFormHttpMessageConverter->Jackson2ObjectMapperBuilder
  4. configureMessageConverters()->Jackson2ObjectMapperBuilder
  5. potentiallyRegisterModule()->Jackson2ObjectMapperBuilder
  6. WebMvcConfigurationSupport->addDefaultHandlerExceptionResolver()->AllEncompassingFormHttpMessageConverter->Jackson2ObjectMapperBuilder
  7. 2 times: WebMvcConfigurationSupport->addDefaultHttpMessageConverters()->AllEncompassingFormHttpMessageConverter->Jackson2ObjectMapperBuilder
  8. 12 times: EndpointMBeanExporter (Spring Boot Actuator)

I'd recommend either using application.properties to configure Jackson or, if you need more control, declaring your own Jackson2ObjectMapperBuilder bean. In either case, you end up with a Jackson2ObjectMapperBuilder bean in the application context that can then be used by other components to create ObjectMapper s with your desired configuration or to apply that configuration to any existing ObjectMapper s.

Edit: there's an issue open to improve Actuator's ObjectMapper usage.

You can configure Jackson using spring boot application.properties .

See class org.springframework.boot.autoconfigure.jackson.JacksonProperties or using Spring Tool Suite, simply edit your application.properties , start typing spring.jackson. then hit Ctrl-Space to see the available properties.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM