关于在Spring中注册自定义的PropertyEditor
来源:互联网 发布:js cookie 编辑:程序博客网 时间:2024/06/05 22:38
考虑下面两个类:
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;}}
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 id="sample" class="document.six.test.DependsOnExoticType"><property name="type" value="aNameForExoticType" /></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" /></map></property></bean>
2 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分析
- Android Studio 报错:Failed to find:com.android.support:appcompat-v7:21.+
- 用JS打开新窗口,防止被浏览器阻止的解决方法
- 好几天来没写了。不知道该说什么好。
- c,c++输入流
- asp.net中js前台为span或后台lable,或Literal控件赋值
- 关于在Spring中注册自定义的PropertyEditor
- uc/os-II的内存改进与实现TLSF算法的详解,移植实现(二)
- Axis2 and CXF的比较
- C++中,malloc/free和new/delete的区别
- android attr到theme的内在关系
- STL 之 stack
- FileOutputStream和FileInputStream使用方法说明
- GCD笔记
- Python基础学习篇—dir()函数