Example:
The target property is java.util.Date, but we can only inject String "2016-04-24"
<property name="date" value="2016-04-24"></property>
So we need a customEditorConfigurer
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <!-- key: target property's class --> <!-- value: PropertyEditor bean --> <entry key="java.util.Date"> <!-- Inner Bean --> <bean class="com.gvace.util.DatePropertyEditor"> <property name="format" value="yyyy-MM-dd"></property> </bean> </entry> </map> </property> </bean> <!-- Use inner Bean instead --> <!-- <bean id="datePropertyEditor" class="com.gvace.util.DatePropertyEditor"></bean> -->
Create custom PropertyEditor, which extends PropertyEditorSupport
package com.gvace.util; import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; //extends PropertyEditorSupport public class DatePropertyEditor extends PropertyEditorSupport{ private String format; @Override public void setAsText(String text) throws IllegalArgumentException { System.out.println("PropertyEditor:"+text); try { Date date = new SimpleDateFormat(format).parse(text); this.setValue(date); } catch (ParseException e) { e.printStackTrace(); throw new IllegalArgumentException("IllegalArgumentException"+text); } } public String getFormat() { return format; } public void setFormat(String format) { this.format = format; } }
No comments:
Post a Comment