ITEEDU

Spring Gossip: CustomEditorConfigurer

Spring的框架中为您提供了一个 BeanFactoryPostProcessor 的 实作类别:org.springframework.beans.factory.config.CustomEditorConfigurer。这个类 别可以读取实作java.beans.PropertyEditor接口的类别,并依当中的实作,将字符串值转换为指定的对象,用此可以简化XML档案中一 长串的Bean设定。

举个例子来说,假设您现在设计了两个类别:
User.java
package onlyfun.caterpillar;

public class User {
private String name;
private int number;

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}

HelloBean.java
package onlyfun.caterpillar; 

public class HelloBean {
private String helloWord;
private User user;

public HelloBean() {
}

public void setHelloWord(String helloWord) {
this.helloWord = helloWord;
}
public String getHelloWord() {
return helloWord;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}
}
依最基本的设定方式,您要在Bean定义档中作以下的设定,以完成依赖注入:
beans-config.xml
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="userBean" class="onlyfun.caterpillar.User">
<property name="name">
<value>Justin</value>
</property>
<property name="number">
<value>5858588</value>
</property>
</bean>

<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!</value>
</property>
<property name="user">
<ref bean="userBean"/>
</property>
</bean>
</beans>
您可以实作java.beans.PropertyEditor接口,但更方便的是继承 java.beans.PropertyEditorSupport,PropertyEditorSupport实作了PropertyEditor介 面,您可以重新定义它的setAsText()方法,这个方法传入一个字符串值,您可以根据这个字符串值内容来建立一个User对象,例如:
UserEditor.java
package onlyfun.caterpillar;

import java.beans.PropertyEditorSupport;

public class UserEditor extends PropertyEditorSupport {
public void setAsText(String text) {
String[] strs = text.split(",");
int number = Integer.parseInt(strs[1]);

User user = new User();
user.setName(strs[0]);
user.setNumber(number);

setValue(user);
}
}
接下来您可以在Bean定义档中这么使用:
beans-config.xml
<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE beans PUBLIC "-//SPRING/DTD BEAN/EN"
"http://www.springframework.org/dtd/spring-beans.dtd">

<beans>
<bean id="configBean" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="onlyfun.caterpillar.User">
<bean id="userEditor" class="onlyfun.caterpillar.UserEditor"/>
</entry>
</map>
</property>
</bean>

<bean id="helloBean" class="onlyfun.caterpillar.HelloBean">
<property name="helloWord">
<value>Hello!</value>
</property>
<property name="user">
<value>Justin,5858588</value>
</property>
</bean>
</beans>
只要是User类型的属性,现在可以使用"Justin,5858588"这样的字符串来设定,CustomEditorConfigurer会加载 customEditors属性中设定的key-value,根据key得知要使用哪一个PropertyEditor来转换字符串值为对象,藉此可以简化 一些Bean属性文件的设定。