Introducing Spring 3 Type Conversion
In Spring 3.0, a general type conversion system was introduced, which resides under the package
org.springframework.core.convert. In addition to providing an alternative to PropertyEditor support,
the type conversion system can also be configured to convert between any Java types and POJOs (while
PropertyEditor is focused on converting String representations in the properties file into Java types).
Implementing a Custom Converter
To see the type conversion system in action, let's revisit the previous example and use the same Contact
class. Suppose this time we want to use the type conversion system to convert the date in String format
into the Contact's birthDate property, which is of JodaTime's DateTime type. To support the conversion,
instead of creating a custom PropertyEditor, we create a custom converter by implementing the
org.springframework.core.convert.converter.Converter<S,T> interface. Listing 14-6 shows the
custom converter.
Listing 14-6. Custom DateTime Converter
package com.apress.prospring3.ch14.converter;
import javax.annotation.PostConstruct;
import
org.joda.time.DateTime;
import
org.joda.time.format.DateTimeFormat;
import
org.joda.time.format.DateTimeFormatter;
import
org.springframework.beans.factory.annotation.Autowired;
import
org.springframework.core.convert.converter.Converter;
public class StringToDateTimeConverter
implements Converter<String, DateTime> {
private static final String DEFAULT_DATE_PATTERN = "yyyy-MM-dd";
private DateTimeFormatter dateFormat;
private String datePattern = DEFAULT_DATE_PATTERN;
public String getDatePattern() {
return datePattern;
}
@Autowired(required=false)
public void setDatePattern(String datePattern) {
this.datePattern = datePattern;
}
@PostConstruct
public void init() {
dateFormat = DateTimeFormat.forPattern(datePattern);
}
public DateTime convert(String dateString) {
Search WWH :
Custom Search
Previous Page
Spring Framework 3 Topic Index
Next Page
Spring Framework 3 Bookmarks
Home