Tuesday, 28 June 2011

Using the Spring 3 Converter Interface

Yesterday’s blog covered Spring’s older property editor based conversion mechanism. Spring 3 introduces the new org.springframework.core.convert package that provides a complete conversion system, which offers much more functionality than previously available. This blog reimplements yesterday’s idea of regular expression conversion using the Converter interface; a fundamental interface of the new mechanism.

  package org.springframework.core.convert.converter;

public interface Converter<S, T> {

T convert(S source);

In using the above to implement the regular expression conversion that I talked about yesterday, the PropertyEditorSupport subclass can be replaced by a Convertor implementation:

public class RegexConverter implements Converter<String, Pattern> {

public Pattern convert(String source) {

return Pattern.compile(source);

Having written the custom converter, we now need to tell Spring about it. The XML file below both registers the DomainName business object from yesterday, and the custom converter class with Spring’s default conversion service class: org.springframework.context.support.ConversionServiceFactoryBean. If a conversion service is not registered with Spring, the original property editor based system is used.

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"

 <!-- Declare our bean -->
 <bean id="domainNameTest" class="miscillaneous.conversionservice.DomainName">
  <property name="pattern">

 <!-- The pattern property above won't take a string so we -->
 <!-- need to declare one of these -->
 <bean id="conversionService"
     <property name="converters">
             <bean class="miscillaneous.conversionservice.RegexConverter"/>
             <!-- TODO Add other converter in here -->

Both the DomainName class and the main(...) code can be found in yesterday’s blog.

No comments: