One of the nice features I’ve grown to love recently while using the Spring framework is the Spring conversion system. Where the Spring conversion system shines in my opinion is in MVC applications. When you create a Spring MVC application using annotation based configuration, you’ll have something like this in your servlet application context:
<mvc:annotation-driven/>
This line will register Spring’s default conversion service instance using org.springframework.format.support.FormattingConversionServiceFactoryBean which registers default converters and formatters. This class can easily be extended to provide your own converters and formatter. When you create a Spring MVC application using Spring Roo, this is done for you automatically. What you end up with is something like this in your servlet application context:
<mvc:annotation-driven conversion-service="applicationConversionService"/> <bean class="org.example.ApplicationConversionServiceFactoryBean" id="applicationConversionService"/>
What we’ve done here (or Roo if that’s what you’re using) is register a custom conversion service with id=”applicationConversionService”. With a Roo managed project, it will manage an ITD with some converters for converting things like composite key types into JSON strings which it also encodes using Base64, which can be useful for referencing an entity ID by a composite key within your MVC application.
Let’s look at creating a custom converter for converting a JSON collection from a String into a List<Type> using Jackson. Type being whatever type you want, be it your own or other.
public class ApplicationConversionServiceFactoryBean extends FormattingConversionServiceFactoryBean {
private Log log = LogFactory.getLog(this.getClass());
@Override
protected void installFormatters(FormatterRegistry registry) {
super.installFormatters(registry);
registry.addConverter(getJSONCollectionToListConverter());
}
public Converter<String, List<MyType>> getJSONCollectionToListConverter() {
return new Converter<String, List<MyType>>() {
@Override
public List<MyType> convert(String source) {
ObjectMapper mapper = new ObjectMapper();
List<MyType> myTypeList = null;
try {
myTypeList = mapper.readValue(source, new TypeReference<List<MyType>>() {});
} catch (Exception e) {
if(log.isErrorEnabled())
log.error("Error converting JSON collection to List<MyType>.", e);
}
return myTypeList;
}
};
}
}
As you can see, it’s quite simple to register your own converter.
Pingback: String to Date Converter with Spring’s Conversion Service | Patrick Grimard's Java Blog