什么是属性编辑器:自定义属性编辑器就是将Spring的字符串转换成相对应的对象进行注入,Spring已经有了内置的属性编辑器,我们可以自己定义属性编辑器。
如何定义属性编辑器:
(1)继承PropertyEditorSupport,重写setAsText()方法。
package com.bjsxt.spring;
import java.beans.PropertyEditorSupport; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date;
/** * java.util.Date属性编辑器 * @author Administrator * */ public class UtilDatePropertyEditor extends PropertyEditorSupport {
private String format="yyyy-MM-dd";
@Override public void setAsText(String text) throws IllegalArgumentException { System.out.println("UtilDatePropertyEditor.saveAsText() -- text=" + text);
SimpleDateFormat sdf = new SimpleDateFormat(format); try { Date d = sdf.parse(text); this.setValue(d); } catch (ParseException e) { e.printStackTrace(); } }
public void setFormat(String format) { this.format = format; }
} |
(2)将属性编辑器注册到Spring中。
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"> <map> <entry key="java.util.Date"> <bean class="com.bjsxt.spring.UtilDatePropertyEditor"> <property name="format" value="yyyy-MM-dd"/> </bean> </entry> </map> </property> </bean> |