spring配置文件的小技巧
spring配置的对象一些属性在XML 中写为String 类型,但实际JAVA 类型中要求注入的是一个其他的对象类型,需要对此做出转换。属性编辑器就是完成这个转换功能的。
比如需要注入一个Date对象:
?123<bean id="demo" class="com.woniu.Demo" > <property name="date" value="2008-08-01"/> </bean> 上述配置肯定报错,采用属性编辑器就可以自动转换成Date对象。但前提是需要实现这个转换类。实现方法如下:
?12345678910111213public class DatePropertyEditor extends PropertyEditorSupport { //继承spring的属性编辑类,重写setAsText方法 @Override public void setAsText(String text) throws IllegalArgumentException { SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd"); try { this.setValue(format.parse(text)); } catch (ParseException e) { e.printStackTrace(); } } }?12345678910<!-- 构造属性编辑器 --><bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date"> <bean class="com.woniu.DatePropertyEditor" /> </entry> </map> </property> </bean> 经过上述配置后就可注入成功。