return dateFormat.parseDateTime(dateString);
}
}
As shown in Listing 14-6, we implement the interface Converter<String, DateTime>, which means
the converter is responsible for converting a String (the source type S) to a DateTime type (the target type
T). The injection of the date-time pattern is optional, by annotating it with @Autowired(required=false).
If not injected, the default pattern yyyy-MM-dd is used. Then, in the initialization method (the init()
method annotated with @PostConstruct), an instance of JodaTime's DateTimeFormat class is constructed,
which will perform the conversion based on the specified pattern. Finally, the convert() method is
implemented to provide the conversion logic.
Configuring ConversionService
To use the conversion service instead of PropertyEditor, we need to configure an instance of the
org.springframework.core.convert.ConversionService interface in Spring's ApplicationContext. Listing
14-7 shows the configuration file (conv-service-app-context.xml).
Listing 14-7. Configuration of ConversionService
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.1.xsd">
<context:annotation-config/>
<bean id="conversionService"
class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<list>
<bean class="com.apress.prospring3.ch14.converter.StringToDateTimeConverter"/>
</list>
</property>
</bean>
<bean id="clarence" class="com.apress.prospring3.ch14.domain.Contact"
p:firstName="Clarence"
p:lastName="Ho"
p:birthDate="1978-08-09"
p:personalSite="http://www.clarence.com"
/>
</beans>
As shown in Listing 14-7, we instruct Spring to use the type conversion system by declaring a
conversionService bean with the class ConversionServiceFactoryBean. If no conversion service bean is
defined, Spring will use the PropertyEditor-based system.
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home