How to configure MappingJacksonHttpMessageConverter while using spring annotation-based configuration?
Use the WebMvcConfigurer.configureMessageConverters()
method:
Configure the HttpMessageConverters to use [...] If no message converters are added to the list, default converters are added instead.
With @Configuration
you have:
@Configuration
class MvcConf extends WebMvcConfigurationSupport {
protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(converter());
addDefaultHttpMessageConverters(converters);
}
@Bean
MappingJacksonHttpMessageConverter converter() {
MappingJacksonHttpMessageConverter converter = new MappingJacksonHttpMessageConverter()
//do your customizations here...
return converter;
}
}
Call to addDefaultHttpMessageConverters()
is required because the defaults are not applied when using custom converters.
IMPORTANT NOTE You must remove @EnableWebMvc
for your converters to be configured if you extend WebMvcConfigurationSupport.
The customization of the spring mvc servlet configuration only in java code can be accomplished in multiple ways.
The simplest one seems to be extending your @Configuration
annotated class with WebMvcConfigurerAdapter
:
@Configuration
@EnableWebMvc
public class ApplicationSpringConfig extends WebMvcConfigurerAdapter {
@Override
public void configureMessageConverters( List<HttpMessageConverter<?>> converters ) {
converters.add(converter());
}
@Bean
MappingJackson2HttpMessageConverter converter() {
// [...]
}
}
Notice that this is lot like the example provided by the answer of Tomasz Nurkiewicz.
However using WebMvcConfigurationSupport
instead of WebMvcConfigurerAdapter
is more appropriate for Advanced Customizations. That was the case if you needed to also add the default converters.
See the Spring documentation Customizing the Provided Configuration