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> {
@Override
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" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- Declare our bean --> <bean id="domainNameTest" class="miscillaneous.conversionservice.DomainName"> <property name="pattern"> <value>[a-zA-Z0-9\.]+(com|co.uk)</value> </property> </bean> <!-- The pattern property above won't take a string so we --> <!-- need to declare one of these --> <bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters"> <list> <bean class="miscillaneous.conversionservice.RegexConverter"/> <!-- TODO Add other converter in here --> </list> </property> </bean> </beans>
Both the DomainName class and the main(...) code can be found in yesterday’s blog.
No comments:
Post a comment