62,621
社区成员
发帖
与我相关
我的任务
分享
package entity;
import java.io.Serializable;
import java.util.Date;
@SuppressWarnings("serial")
public class Day implements Serializable{
private Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<bean id="day" class="entity.Day">
<!--这里的value我输入字符串类型的日期格式-->
<property name="date" value="2008-08-08"></property>
</bean>
<!--配置转换器-->
<bean id="datePropertyConvert" class="util.DatePropertyConvert"></bean>
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<!--指定转化器要转化的目标类型-->
<entry key="java.util.Date" value-ref="datePropertyConvert"></entry>
</map>
</property>
</bean>
</beans>
package util;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DatePropertyConvert extends PropertyEditorSupport {
private String formart = "yyyy-MM-dd";
@Override
public void setAsText(String text) throws IllegalArgumentException {
//获取日期格式化对象
SimpleDateFormat sdf=new SimpleDateFormat(formart);
try {
//将字符串类型的日期转换成Date类型
Date date = sdf.parse(text);
setValue(date);
} catch (ParseException e) {
e.printStackTrace();
}
}
@Override
public void setValue(Object value) {
super.setValue(value);
}
@Override
public String getAsText() {
return super.getAsText();
}
}
package test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import entity.Day;
public class Test {
public static void main(String[] args) {
ApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml");
Day d=(Day)ctx.getBean("day");
System.out.println(d.getDate());
}
}
改过之后运行通过了
谢谢各位
<bean id="datePropertyConvert" class="util.DatePropertyConvert">
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<!--指定转化器要转化的目标类型-->
<entry key="java.util.Date" value-ref="datePropertyConvert"></entry>
</map>
</property>
</bean>
</bean>