spring中日期型属性的注入时,会报类型转换异常
如:
package com.spring
import java.util.Date;
public class UserManager {
private Date dataValue;
public Date getDataValue() {
return dataValue;
}
public void setDataValue(Date dataValue) {
this.dataValue = dataValue;
}
public String toString(){
return "dataValue: " + dataValue;
}
}
上面代码中,需要对日期型属性进行注入
beans.xml
<bean id="userManager" class="com.spring.UserManager">
<property name="dataValue">
<value>2012-11-15</value>
</property>
</bean>
测试代码:
@Test
public void testDate(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("beans.xml");
UserManager userManager = (UserManager)ctx.getBean("userManager");
System.out.println(userManager);
}
如果直接这样使用程序则会报异常,类型转换不成功
Spring提供两种方式:
一、 使用自定义属性编辑器通过继承PropertyEditorSupport,重写setAsText方法
二、通过注册Spring自带的属性编辑器CustomDateEditor
自定义方式:
首先编写自定义的属性编辑器:
package com.spring;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DatePropertyEditor extends PropertyEditorSupport {
private String format = "yyyy-MM-dd";
public void setFormat(String format) {
this.format = format;
}
public void setAsText(String arg0) throws IllegalArgumentException {
System.out.println("arg0: " + arg0);
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date d = sdf.parse(arg0);
this.setValue(d);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
然后将自定义属性编辑器注册到Spring中:
<!-- 自定义属性编辑器 -->
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.spring.DatePropertyEditor">
<property name="format" value="yyyy-MM-dd"/>
</bean>
</entry>
</map>
</property>
</bean>
另一种是通过注册Spring自带的属性编辑器:
package com.spring;
import java.util.Date;
import java.text.SimpleDateFormat;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;
public class DatePropertyEditorRegistrar implements PropertyEditorRegistrar{
public void registerCustomEditors(PropertyEditorRegistry registry) {
registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
}
}
<!-- 注册Spring自带编辑器 -->
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="com.bjsxt.spring.DatePropertyEditorRegistrar"></bean>
</list>
</property>
</bean>
通过以上两种配置就可以解决日期类型的转换问题,其他类型也类似。
PS: 记录一下,以备查询,有不对的地方,还请不吝赐教,谢谢!