关于在Spring中注册自定义的PropertyEditor
来源:互联网 发布:淘宝首页的广告位费用 编辑:程序博客网 时间:2024/06/04 23:06
考虑下面两个类:
ExoticType:
package document.six.test; public class ExoticType { private String name; public ExoticType(String name) { this.name = name; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
DpendsOnExoticType:
package document.six.test; public class DependsOnExoticType { private ExoticType type; public void setType(ExoticType type) { this.type = type; } public ExoticType getType() { return type; }}
再配置一下Spring的xml
<bean class="document.six.test.DependsOnExoticType" id="sample"> <property name="type" value="aNameForExoticType"></property></bean>
再写一个测试方法:
package document.six.test; import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext; public class SpringTest { public static void main(String args[]) { ApplicationContext ctx = new ClassPathXmlApplicationContext( "springMVC.xml"); DependsOnExoticType sample = (DependsOnExoticType) ctx .getBean("sample"); System.out.println(sample.getType().getName()); }}
输出结果为:
aNameForExoticType
看看上面的xml文件,我们为DependsOnExoticType的type属性设置了一个String,它却自动的转换成了ExoticType对象
关键在于ExoticType的构造函数,因为它有一个带String参数的构造函数
若想要改变默认的PropertyEditor,可以添加自定义的来覆盖它。在添加时可以使用一个自动检测的机制:也就是需要遵照一定的规则
具体的规则是:PropertyEditor类和标准的 JavaBeans在同一个包下,并且他们PropertyEditor的类名是JavaBeans的类名加上“Editor”,比如:
public class ExoticTypeEditor extends PropertyEditorSupport { public void setAsText(String text) { setValue(new ExoticType(text.toUpperCase())); }}
可以看到这个PropertyEditor就是遵照了以上的命名规则,并且和ExoticType放在同一个包中,所以无需额外的配置就可以得到下面的输出:
ANAMEFOREXOTICTYPE
那么若没有符合以上规则的话,怎么办呢?可以通过org.springframework.beans.factory.config.CustomEditorConfigurer这个Bean来注册
为这个Bean配置customEditors属性,该属性是一个Map,将我们需要注册的PropertyEditors都注入到这个Map里就可以了
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <property name="customEditors"><map> <entry key="document.six.test.ExoticType" value="document.six.test.ExoticType2Editor"> </entry></map> </property></bean>
0 0
- 关于在Spring中注册自定义的PropertyEditor
- 关于在Spring中注册自定义的PropertyEditor
- Spring的自定义PropertyEditor
- spring配置自定义的PropertyEditor
- spring 强大的PropertyEditor
- 探秘Spring的PropertyEditor
- 在自定义标签子类获取Spring中注册的bean
- Spring源代码分析(5)---propertyEditor(移花接木的自定义属性编辑器)
- Spring的FactoryBean与PropertyEditor
- Spring IOC 自定义属性编辑器PropertyEditor
- Spring PropertyEditor 相关类的模拟实现
- Spring Bean包装类案例之自定义PropertyEditor
- 在Mac和iOS中注册自定义的URL Scheme
- SpringMVC 自定义全局PropertyEditor
- SpringMVC 自定义全局PropertyEditor
- spring propertyEditor 小总结
- Spring之PropertyEditor
- Spring PropertyEditor分析
- JAVA将执行sql结果导入excel
- java实现软件程序开机自动启动和创建程序的桌面快捷方式源代码
- Linux——关于LUN和存储卷的区别详解
- 数据结构第四章字符串与多维数组 知识导图
- Oracle DML DDL DCL TCL
- 关于在Spring中注册自定义的PropertyEditor
- IO-00. Hello World! (5)
- 树和二叉树 知识导图
- IO-01. 表格输出(5)
- 设计模式:单例模式
- uva 138 Street Numbers(打表大法好)
- Linux 实现自动安装服务组件以及优化内核参数
- Application对象——记录历史访问
- 两个不同数据库之间的两个表如何关联起来查询数据