Spring的框架中為您提供了一個 BeanFactoryPostProcessor
的
實作類別:org.springframework.beans.factory.config.CustomEditorConfigurer。這個類
別可以讀取實作java.beans.PropertyEditor介面的類別,並依當中的實作,將字串值轉換為指定的物件,用此可以簡化XML檔案中一
長串的Bean設定。
舉個例子來說,假設您現在設計了兩個類別:
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; } }
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定義檔中作以下的設定,以完成依賴注入:
<?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物件,例如:
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定義檔中這麼使用:
<?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屬性檔的設定。 |