Sping中自定義屬性編輯器
Spring通過PropertyEdit(屬性編輯器) 可以將字符串轉換為真實類型。通過CustomEditorConfigurer ,ApplicationContext 可以很方便的支持自定義
PropertyEdit。
MyType.java
package com.cao.spring.applicationContext;
public class MyType {
private String text;
public MyType(String text){
this.text = text;
}
public String getText(){
return this.text;
}
}
DependsOnType.java
package com.cao.spring.applicationContext;
public class DependsOnType {
private MyType type;
public MyType getType() {
return type;
}
public void setType(MyType type) {
this.type = type;
}
}
//自定義的屬性編輯器MyTypeEdit.java
package com.cao.spring.applicationContext;
public class MyTypeEdit extends java.beans.PropertyEditorSupport{
//提供一種對字符串的轉換策略
private String format;
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
//覆蓋父類(PropertyEditorSupport)的setAsText方法。
public void setAsText(String text) {
if(format!=null && format.equals("upperCase")){
System.out.println("修改前的樣子:"+text);
text=text.toUpperCase();
}
//獲得編輯前的類型
System.out.println("獲得編輯前的類型 "+text.getClass().getSimpleName());
//包裝成真實類型
MyType type = new MyType(text);
//注入包裝后的類型
setValue(type);
}
}
配置bean propertyEdit.xml
<beans>
<bean id="myBean" class="com.cao.spring.applicationContext.DependsOnType">
<!-- type的真實類型是 MyType 但這里指定的是一個普通的String -->
<property name="type">
<value>abc</value>
</property>
</bean>
</beans>
將屬性編輯器配置進來 plugin.xml
<bean id="aaa" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map> <!-- key指定了轉換后的類型 -->
<entry key="com.cao.spring.applicationContext.MyType">
<!-- 內部bean 配置了自定義的屬性編輯器 -->
<bean class="com.cao.spring.applicationContext.MyTypeEdit">
<!-- 配置字符串的轉換策略 -->
<property name="format" value="upperCase"/>
</bean>
</entry>
</map>
</property>
</bean>
測試類:
public class MyEditorTest {
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(new String[]{"application/plugin.xml","application/propertyEdit.xml"});
DependsOnType type= (DependsOnType) ctx.getBean("myBean");
System.out.println(type.getType().getClass().getSimpleName());
System.out.println(type.getType().getText());
}
}
//輸出結果:
修改前的樣子:abc獲得編輯前的類型 StringMyTypeABC
posted on 2008-05-30 12:44 shine_panda 閱讀(123) 評論(0) 編輯 收藏