spring 强大的PropertyEditor

    今天看了一下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;

}

}

<bean id="user" class="com.lhacker.domain.User">

<property name="name" value="Dylan" />

<property name="son" value="Dylan的儿子"/>

</bean>

不需要配置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()));

}

}

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> 

<property name="customEditors"> <map> <entry key="com.lhacker.domain.Son" 

value="com.lhacker.controller.util.ExoticTypeEditor" /> </map> </property> 

</bean>

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

还有另一种方式

public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {

@Override

public void registerCustomEditors(PropertyEditorRegistry registry) {

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

}

}

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">

<property name="propertyEditorRegistrars">

<list>

<ref bean="customPropertyEditorRegistrar" />

</list>

</property>

</bean>

<bean id="customPropertyEditorRegistrar" class="com.lhacker.controller.util.CustomPropertyEditorRegistrar" />

猜你喜欢

转载自lhacker.iteye.com/blog/1608100
今日推荐