Spring DI注入的时候可以把普通属性注入进来,但是像Date类型的就无法被识别。这时可以通过Spring的属性编辑器把配置文件中的字符串转化成相应的对象进行注入。
Spring有自带的属性编辑器,我们也可以写自定义的属性编辑器
自定义属性编辑器:
继承java.beans.PropertyEditorSupport类,重写其中的setAsText(String text)方法。
再把自定义的属性编辑器注入到Spring中。
1. JavaBean类
package com.dxc.zidingyishuxingbianjiqi;
import java.util.Date;
public class DateBean {
private Date dataValue;
public Date getDataValue() {
return dataValue;
}
public void setDataValue(Date dataValue) {
this.dataValue = dataValue;
}
}
2.自定义属性编辑器:
package com.dxc.zidingyishuxingbianjiqi;
import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* java.util.Date属性编辑器
*/
public class UtilDatePropertyEditor extends PropertyEditorSupport {
private String format="yyyy-MM-dd";
@Override
public void setAsText(String text) throws IllegalArgumentException {
// TODO Auto-generated method stub
SimpleDateFormat sdf=new SimpleDateFormat(format);
try {
Date date=sdf.parse(text);
this.setValue(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void setFormat(String format){
this.format=format;
}
}
3. 配置自定义的属性编译器
<?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:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- 将bean中的dataValue赋值为2008-8-15,spring会认为是String类型,无法转换为Date -->
<bean id="dateBean" class="com.dxc.zidingyishuxingbianjiqi.DateBean">
<property name="dataValue">
<value>2008-08-15</value>
</property>
</bean>
<!-- 自定义属性编辑器 -->
<bean id="customerEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.dxc.zidingyishuxingbianjiqi.UtilDatePropertyEditor">
<property name="format">
<value>yyyy-MM-dd</value>
</property>
</bean>
</entry>
</map>
</property>
</bean>
</beans>
3.测试结果,
package com.dxc.zidingyishuxingbianjiqi;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestDate {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext ac=new ClassPathXmlApplicationContext("com/dxc/zidingyishuxingbianjiqi/applicationContext.xml");
DateBean bean=(DateBean) ac.getBean("dateBean");
System.out.println(bean.getDataValue());
}
}
注释掉自定义编辑器,会报错,把String转换Date错误。