你的位置:首页 > Java教程

[Java教程]Spring类型转换 ConversionSerivce Convertor


以String转Date为例:
 
定义转换器: 
 
import java.text.ParseException;import java.util.Date;import org.apache.commons.lang.time.DateUtils;import org.springframework.core.convert.converter.Converter;public class String2DateConverter implements Converter<String, Date> {  private String format = "yyyy-MM-dd";  public void setFormat(String format){    this.format = format;  }  @Override  public Date convert(String arg0) {    try {      return DateUtils.parseDate(arg0, new String[] { format });    } catch (ParseException e) {      return null;    }  }}

 
配置Spring:
 
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <property name="converters">  <list>   <bean class="com.xxx.String2DateConverter"/>  </list> </property></bean>