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" />

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章