Why do we need to specify HttpMessageConverter in Spring?

Viewed 2570

Now I am working with Spring MVC and I had and issue that some methods of controller were not returning data and throw HttpMediaTypeNotAcceptableException and my methods were producing text/plain . I discovered in my config that someone overrided configureMessageConverters(List<HttpMessageConverter<?>> converters) of WebMvcConfigurerAdapter

@Autowired
private MappingJackson2HttpMessageConverter jsonConverter;

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    converters.addAll(Collections.singletonList(jsonConverter));
}

I read some articles and discovered that : By default, the following HttpMessageConverters instances are pre-enabled:

ByteArrayHttpMessageConverter – converts byte arrays
StringHttpMessageConverter – converts Strings
ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
SourceHttpMessageConverter – converts javax.xml.transform.Source FormHttpMessageConverter – converts form data to/from a MultiValueMap.
Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML (added only if JAXB2 is present on the classpath)
MappingJackson2HttpMessageConverter – converts JSON (added only if Jackson 2 is present on the classpath)
MappingJacksonHttpMessageConverter – converts JSON (added only if Jackson is present on the classpath)
AtomFeedHttpMessageConverter – converts Atom feeds (added only if Rome is present on the classpath)
RssChannelHttpMessageConverter – converts RSS feeds (added only if Rome is present on the classpath)

I removed that code and everything started working fine. So any one have and idea why it was done, I mean why that code was written? Because as I see everything is working out of the box and that code was useless. So the question is:

Why do we need to specify HttpMessageConverter in Spring?

1 Answers

MappingJackson2HttpMessageConverter was added in 3.1.2 and it may not have been autodiscovered at that version yet.

The code may have been written for an older version, becoming obsolete as the libraries have been upgraded. It could also have been written by someone that didn't know that it's automatic with newer versions (if you copy paste code randomly from the web, you don't really know what kind of monster you end up creating).

You don't need to configure additional converters unless you're doing something specific which isn't configured by default already. That should be quite rare these days, if you're not doing anything exotic.

My question is why doesn't it work if you configure it manually. It's unnecessary, but that doesn't mean it's not allowed. It shouldn't break things.

Related