Everyone is saying @EnableWebMvc is the culprit.
But, no one is saying with WebMvc how to resolve this issue.
So, to answer the question, yes, there is a way to resolve this issue by not removing the @EnableWebMvc.
Before moving into the answer, let's understand a few concepts:
- HttpMessageConverters -> These are the ones that convert Java Objects from and to JSON/XML.
- By default, Spring boot will add the following converters:
- ByteArrayHttpMessageConverter
- StringHttpMessageConverter
- ResourceHttpMessageConverter
- SourceHttpMessageConverter
- FormHttpMessageConverter
- Jaxb2RootElementHttpMessageConverter
- MappingJackson2XmlHttpMessageConverter
- MappingJackson2HttpMessageConverter
- So, whenever we are converting the java object into JSON, Spring will go through this list of converters one by one in order and picks the relevant one to use for conversion.
- Now, if we add our custom MappingJackson2HttpMessageConverter to this list as the last element, then Spring will not come to it because before reaching our converter(9th element), there is the default converter at the 7th index.
- So, to resolve this issue, we need to remove the default MappingJackson2HttpMessageConverter and we need to add our custom converter.
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
// Remove the default MappingJackson2HttpMessageConverter
converters.removeIf(converter -> {
String converterName = converter.getClass().getSimpleName();
return converterName.equals("MappingJackson2HttpMessageConverter");
});
// Add your custom MappingJackson2HttpMessageConverter
MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
converter.setObjectMapper(objectMapper);
converters.add(converter);
WebMvcConfigurer.super.extendMessageConverters(converters);
}
}
Note: Please don't use te configureMessageConverters() method instead of the extendMessageConverters() method from WebMvcConfigurer, because the configure method will remove all the existing converters are installed by default.
Hope it will help someone like me who has wasted some hours debugging the issue :)
@EnableWebMvcwas the culprit.