首页 > 代码库 > 关于在Spring中注册自定义的PropertyEditor

关于在Spring中注册自定义的PropertyEditor

考虑下面两个类:

ExoticType:

package document.six.test;

public class ExoticType {
	private String name;

	public ExoticType(String name) {
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


DpendsOnExoticType:
package document.six.test;

public class DependsOnExoticType {
	private ExoticType type;

	public void setType(ExoticType type) {
		this.type = type;
	}

	public ExoticType getType() {
		return type;
	}
}


再配置一下Spring的xml

	<bean id="sample" class="document.six.test.DependsOnExoticType">
		<property name="type" value=http://www.mamicode.com/"aNameForExoticType" />>


再写一个测试方法:

package document.six.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringTest {

	public static void main(String args[]) {
		ApplicationContext ctx = new ClassPathXmlApplicationContext(
				"springMVC.xml");
		DependsOnExoticType sample = (DependsOnExoticType) ctx
				.getBean("sample");
		System.out.println(sample.getType().getName());
	}
}

输出结果为:

aNameForExoticType

看看上面的xml文件,我们为DependsOnExoticType的type属性设置了一个String,它却自动的转换成了ExoticType对象

关键在于ExoticType的构造函数,因为它有一个带String参数的构造函数


若想要改变默认的PropertyEditor,可以添加自定义的来覆盖它。在添加时可以使用一个自动检测的机制:也就是需要遵照一定的规则

具体的规则是:PropertyEditor类和标准的 JavaBeans在同一个包下,并且他们PropertyEditor的类名是JavaBeans的类名加上“Editor”,比如:

public class ExoticTypeEditor extends PropertyEditorSupport {
	public void setAsText(String text) {
		setValue(new ExoticType(text.toUpperCase()));
	}
}

可以看到这个PropertyEditor就是遵照了以上的命名规则,并且和ExoticType放在同一个包中,所以无需额外的配置就可以得到下面的输出:

ANAMEFOREXOTICTYPE


那么若没有符合以上规则的话,怎么办呢?可以通过org.springframework.beans.factory.config.CustomEditorConfigurer这个Bean来注册

为这个Bean配置customEditors属性,该属性是一个Map,将我们需要注册的PropertyEditors都注入到这个Map里就可以了:

	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="document.six.test.ExoticType" value=http://www.mamicode.com/"document.six.test.ExoticType2Editor" />>






关于在Spring中注册自定义的PropertyEditor