介绍
在spring中可以把普通属性注入道对象中,但是Date类型就无法被识别。列如
public class User {
private Date dateValue;
public Date getDateValue() {
return dateValue;
}
public void setDateValue(Date dateValue) {
this.dateValue = dateValue;
}
public static void main(String[] args) {
ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:application-propertyEdtior.xml");
ctx.getBean(User.class);
}
}
xml配置文件
<bean id="user" class="com.property.User" >
<property name="dateValue"><value>2019-06-13</value></property>
</bean>
直接测试上面的main方法会抛出异常,因为User中dateValue中是Date类型,无法转换,为此Spring通过属性编译器来解决问题
自定义属性编辑器
通过继承java.beans.PropertyEditorSupport类,重写public void setAsText(String text) 方法,该类是jdk中方法。
代码如下
public class DatePropertyEditor extends PropertyEditorSupport {
private String format = "yyyy-MM-dd";
@Override
public void setAsText(String text) throws IllegalArgumentException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
Date date = null;
try {
date = sdf.parse(text);
} catch (ParseException e) {
e.printStackTrace();
}
this.setValue(date);
}
}
xml代码如下
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date" value="com.property.DatePropertyEditor">
<!-- 有的书上建议用bean,这里其实必须用value-->
</entry>
</map>
</property>
</bean>
此时再次执行上面的main方法,则可以正常执行
Spring自带编辑器
注册Spring自带的属性编辑器CustomDateEditor,
1.定义属性编辑器
public class DatePropertyEdtiorRegistrar implements PropertyEditorRegistrar {
public void registerCustomEditors(PropertyEditorRegistry propertyEditorRegistry) {
propertyEditorRegistry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
}
}
org.springframework.beans.propertyeditors.CustomDateEditor ,Spring属性编辑器,其实查看源代码就可以得知,此方法和我们上面自己的方法是一样也是继承了PropertyEditorSupport 类
PropertyEditorRegistrar 通过该类注册到属性propertyEditorRegistrars ,这里的缓存其实就是Map
xml代码
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="propertyEditorRegistrars">
<list>
<bean class="com.property.DatePropertyEdtiorRegistrar"> </bean>
</list>
</property>
</bean>
此刻再次执行main方法会发现和之前一样的执行结果。