您的位置:首页 > 编程语言 > Java开发

Spring自定义属性编辑器

2011-07-04 22:53 381 查看
什么是属性编辑器,作用?
* 自定义属性编辑器,spring配置文件中的字符串转换成相应的对象进行注入
spring已经有内置的属性编辑器,我们可以根据需求自己定义属性编辑器

* 如何定义属性编辑器?
* 继承PropertyEditorSupport类,覆写setAsText()方法,参见:UtilDatePropertyEditor.java
* 将属性编辑器注册到spring中,参见:applicationContext-editor.xml package com.bjsxt.spring;import java.beans.PropertyEditorSupport;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class UtilDatePropertyEditor extends PropertyEditorSupport { private String format="yyyy-MM-dd";

@Override
public void setAsText(String text) throws IllegalArgumentException {
System.out.println("UtilDatePropertyEditor.saveAsText() -- text=" + text);

SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
Date d = sdf.parse(text);
this.setValue(d);
} catch (ParseException e) {
e.printStackTrace();
}
} public void setFormat(String format) {
this.format = format;
}}
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- 定义属性编辑器 -->
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.util.Date">
<bean class="com.bjsxt.spring.UtilDatePropertyEditor">
<property name="format" value="yyyy-MM-dd"/>
</bean>
</entry>
</map>
</property>
</bean>

<!--
<bean id="utilDatePropertyEditor" class="com.bjsxt.spring.UtilDatePropertyEditor"></bean>
-->
</beans>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: