Spring 配置String转Date

2020-09-11 10:58:16 浏览数 (1)

代码语言:javascript复制
操作步骤:

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

2. 配置 org.springframework.context.support.ConversionServiceFactoryBean converters 

以String转Date为例:

定义转换器:

代码语言:javascript复制
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配置

代码语言:javascript复制
<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
  <property name="converters">
    <list>
      <bean class="com.xxx.String2DateConverter"/>
    </list>
  </property>
</bean>

注解配置:

代码语言:javascript复制
@Bean
ConversionServiceFactoryBean conversionServiceFactoryBean(){
   ConversionServiceFactoryBean factoryBean = new ConversionServiceFactoryBean();
   factoryBean.setConverters(new HashSet(){{add(new String2DateConverter());}});
   return factoryBean;
}

0 人点赞