Why is Spring Boot not using a @Primary Jackson ObjectMapper for JSON serialization on a rest controller?
Whilst the other answers show alternative ways of achieving the same result, the actual answer to this question is that I had defined a separate class that extended WebMvcConfigurationSupport
. By doing that the WebMvcAutoConfiguration
bean had been disabled and so the @Primary ObjectMapper was not picked up by Spring. (Look for @ConditionalOnMissingBean(WebMvcConfigurationSupport.class)
in the WebMvcAutoConfiguration
source.)
Temporarily removing the class extending WebMvcConfigurationSupport
allowed the @Primary
ObjectMapper
to be picked up and used as expected by Spring.
As I couldn't remove the WebMvcConfigurationSupport
extending class permanently, I instead added the following to it:
@Autowired
private ObjectMapper mapper;
@Override
public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
converters.add(new MappingJackson2HttpMessageConverter(mapper));
addDefaultHttpMessageConverters(converters);
super.configureMessageConverters(converters);
}
Spring uses HttpMessageConverters to render @ResponseBody (or responses from @RestController). I think you need to override HttpMessageConverter.
You can do that by extending WebMvcConfigurerAdapter
and override following.
@Override
public void configureMessageConverters(
List<HttpMessageConverter<?>> converters) {
messageConverters.add(new MappingJackson2HttpMessageConverter());
super.configureMessageConverters(converters);
}
Spring documentation