Sunday, June 30, 2013

Spring MVC - Migrating to Jackson 2

This does not really require a blog entry - migrating from Jackson 1.9.x to Jackson 2.x is extremely simple with Spring MVC 3.1+ based applications. The only thing that needs to be done is to replace the 1.9.x jar with Jackson 2.x jar, with the following new entry in a maven pom.xml file (assuming a maven project)


This is pretty remarkable considering the fact that the core Jackson package names have now been refactored from
"org.codehaus.jackson" to "com.fasterxml.jackson".

So how does this Spring MVC handle such migrations internally -

Spring MVC uses a component called a HttpMessageConverter as a strategy interface to convert the request body to an object representation, and to convert the response object representation to a serialized form to be sent back as a response.

Spring MVC registers a series of HttpMessageConverters to handle request bodies, this happens by default when the MVC is activated, typically using a xml Spring bean definition file this way:

<mvc:annotation-driven />

Or, when using new Java Config style of bean definition:

 includeFilters=@Filter(type=FilterType.ANNOTATION, value=Controller.class))
public class WebConfig {


In both cases, a check for the presence of Jackson2 libraries is made by scanning for well-known classes within the jackson2 library:

private static final boolean jackson2Present =
  ClassUtils.isPresent("com.fasterxml.jackson.databind.ObjectMapper", aClassLoader) &&
    ClassUtils.isPresent("com.fasterxml.jackson.core.JsonGenerator", aClassLoader);

and assuming Jackson 2.x libraries are present, an appropriate HttpMessageConverter is registered:

if (jackson2Present) {
 messageConverters.add(new MappingJackson2HttpMessageConverter());

If there happen to be both the 1.9.x jars and the 2.x jars of Jackson in the classpath, then preferentially the 2.x HttpMessageConverter is registered before the 1.9.x HttpMessageConverters.

This way Spring MVC seamlessly handles the upgrade of Jackson libraries

No comments:

Post a Comment