---
title: "spring 强大的PropertyEditor"
author: "LHacker"
date: "2012-07-26T16:52:57Z"
tags: []
categories: ["企业架构"]
slug: "spring-propertyeditor"
draft: false
lastmod: "2012-07-26T16:52:57Z"
id: 1608100
url: "https://lhacker.iteye.com/blog/1608100"
---

今天看了一下spring的Data Binding，觉得挺强大，记录一下，以免忘记。

 

public class User{

private String name;

private Son son;

public Son getSon() {

return son;

}

public void setSon(Son son) {

this.son = son;

}

 

}

 

 

public class Son{

private String name;

public Son(){}

public Son(String name) {

this.name = name;

}

 

}

 

 

&lt;bean id="user" class="com.lhacker.domain.User"&gt;

&lt;property name="name" value="Dylan" /&gt;

&lt;property name="son" value="Dylan的儿子"/&gt;

&lt;/bean&gt;

 

 

不需要配置son的bean，只需要以上的一个配置，spring就会初始化Son,并把“Dylan的儿子"根据Son的有参构造函数，把值绑定在name属性中。

 

 

还可以定义自己的TypeEditor，继承java提供的PropertyEditorSuppor.

 

public class ExoticTypeEditor extends PropertyEditorSupport {

 

@Override

public void setAsText(String text) throws IllegalArgumentException {

setValue(new Son(text.toUpperCase()));

}

 

}

 

 

 

&lt;bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"&gt; 

&lt;property name="customEditors"&gt; &lt;map&gt; &lt;entry key="com.lhacker.domain.Son" 

value="com.lhacker.controller.util.ExoticTypeEditor" /&gt; &lt;/map&gt; &lt;/property&gt; 

&lt;/bean&gt;

 

 

这样，就可以将Son的name属性值绑定为"DYLAN的儿子"。

 

还有另一种方式

 

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

 

@Override

public void registerCustomEditors(PropertyEditorRegistry registry) {

registry.registerCustomEditor(Son.class, new ExoticTypeEditor());

}

 

}

 

&lt;bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"&gt;

&lt;property name="propertyEditorRegistrars"&gt;

&lt;list&gt;

&lt;ref bean="customPropertyEditorRegistrar" /&gt;

&lt;/list&gt;

&lt;/property&gt;

&lt;/bean&gt;

 

&lt;bean id="customPropertyEditorRegistrar" class="com.lhacker.controller.util.CustomPropertyEditorRegistrar" /&gt;