Spring属性编辑器
在spring DI注入的时候可以把普通的属性注入进来,但是像Date类型就无法识别,例如
- Bean类
package mytest.genge.jichu;
import java.util.Date;
public class UserManager {
private Date dateValue;
public Date getDateValue() {
return dateValue;
}
public void setDateValue(Date dateValue) {
this.dateValue = dateValue;
}
@Override
public String toString() {
return "UserManager [dateValue=" + dateValue + "]";
}
}
- spring xml 配置文件
<bean id="userManager" class="mytest.genge.jichu.UserManager">
<property name="dataValue">
<value>2015-03-15</value>
</property>
</bean>
如果直接这样注入,程序则会异常,类型转换不成功,因为在UserManager中的dataValue属性是Date类型,而在xml配置文件中的值确实String类型,当然会抛出异常。
Spring 对此问题提供了两个解决办法
使用自定义属性编辑器
使用自定义属性编辑器,通过继承PropertyEditorSupport重写setAsText方法编写属性编辑器
import java.beans.PropertyEditorSupport; import java.util.Date; import org.springframework.util.StringUtils; public class DatePropertyEditor extends PropertyEditorSupport{ private String format = “yyyy-MM-dd”; public void setFormat(String format){ this.format = format; } public void setAsText(String text) throws Exception { System.out.println("使用自己的编辑器。"); if (text == null || !StringUtils.hasText(text)) { throw new IllegalArgumentException("老大,不能为空啊!"); } else { SimpleDateFormat sdf = new SimpleDateFormat(format); Date date = sdf.parse(text); this.setValue(date); } } }
讲自定义的属性编辑器注册到Spring中
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date"> <!-- 属性类型 --> <bean class="com.stamen.propedit.DatePropertyEditor"> <property name="format" value="yyy-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中
<!-- 注册Spring自带编辑器 --> <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="propertyEditorRegistrars"> <list> <bean class="com.bjsxt.spring.DatePropertyEditorRegistrar"></bean> </list> </property> </bean>