Spring 配置String转Date

操作步骤:

1. 实现 org.springframework.core.convert.converter.Converter 接口

2. 配置
org.springframework.context.support.ConversionServiceFactoryBean converters
 
以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:
 
 xml配置
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  <property name="converters">
    <list>
      <bean class="com.xxx.String2DateConverter"/>
    </list>
  </property>
</bean>

 注解配置:

@Bean
ConversionServiceFactoryBean conversionServiceFactoryBean(){
   ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();
   factoryBean.setConverters(new HashSet(){{add(new String2DateConverter());}});
   return factoryBean;
}

  

posted @ 2016-11-12 14:54  WindWant  阅读(1446)  评论(0编辑  收藏  举报
文章精选列表