自定义属性编辑器,将spring配置文件中的字符串转换成相应的对象进行注入,如日期属性的注入。
spring已经有内置的属性编辑器,我们可以根据需求自己定义属性编辑器
下以创建Date类型的属性编辑器为例说明如何创建属性编辑器。
在setAsText()中将字符串转换为要求的对象,用setValue(obj)将对象注入。
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;
	}
}
用注入的方式向CustomEditorConfigurer的customEditors中注入新建的编辑器。
<!-- 定义属性编辑器 --> <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>
以后时间属性就可以注入了。