您的位置:首页 > 其它

Sping中自定义属性编辑器

2008-05-30 20:44 260 查看
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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: