Both Spring Boot and Springs @EnableWebMvc annotation rely on the WebMvcConfigurationSupport to setup Spring MVC. One recurring headache is this class detects if Jackson is on the classpath and then creates its own ObjectMapper instance and adds it to the MappingJackson2HttpMessageConverter class. Below, you can see the class creates two separate instances based on the availability of jackson2 or jackson2xml.
if (jackson2XmlPresent) {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.xml().applicationContext(this.applicationContext).build();
messageConverters.add(new MappingJackson2XmlHttpMessageConverter(objectMapper));
}
//jaxb2 config removed for clarity
if (jackson2Present) {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().applicationContext(this.applicationContext).build();
messageConverters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}
The challenge with this is that most developers configure their own ObjectMapper instance and may either assume that it will be used by Spring MVC or they forget to write code to inject their ObjectMapper instance into either of the MessageConverter classes above.
From a Spring perspective, it would be nice if we check to see if a ObjectMapper already exists and attempt to use that. We can get around this with Spring Boot though. Does it make sense to have an AutoConfiguration class do this for people or is there a reason why we don't want to do this?
Aucun commentaire:
Enregistrer un commentaire