关于在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="aNameForExoticType" />
	</bean>


再写一个测试方法:

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="document.six.test.ExoticType2Editor" />
			</map>
		</property>
	</bean>






  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值