Spring依赖注入对于Date类型数据的处理

来源:互联网 发布:男士皮鞋推荐知乎 编辑:程序博客网 时间:2024/05/01 22:11
  1. 编写Date数据处理类:继承java.beans.PropertyEditorSupport,覆盖父类中的setAsText方法,相关代码如下:
package com.gengyang.spring;import java.beans.PropertyEditorSupport;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;public class UtilDatePropertyEditor extends PropertyEditorSupport {private String format = "yyyy-MM-dd";public void setAsText(String text) throws IllegalArgumentException {SimpleDateFormat dateFormat = new SimpleDateFormat(format);try {Date date = dateFormat.parse(text);setValue(date);} catch (ParseException e) {e.printStackTrace();}}public void setFormat(String format) {this.format = format;}}
    2.配置Spring配置文件:
<bean id="dateFormat" class="org.springframework.beans.factory.config.CustomEditorConfigurer" ><property name="customEditors"><map><entry key="java.util.Date"><bean class="com.gengyang.spring.UtilDatePropertyEditor"><property name="format" value="yyyy/MM/dd HH:mm:ss"></property></bean></entry></map></property></bean>