属性编辑器

什么是属性编辑器,作用?
 
     spring已经有内置的属性编辑器,它的作用是 spring配置文件中的字符串转换成相应的对象进行注入,
我们可以根据需求自己定义属性编辑器
  
什么时候需要自定义属性编辑器
  某些时候需要自定义,spring内置的属性编辑器,不能把字符串转换成相应的对象。
如注入的日期字符串,不能转换成日期类型注入对象。就需要自定义属性编辑器。


如何定义属性编辑器?
  * 继承PropertyEditorSupport类,覆写setAsText()方法,参见:UtilDatePropertyEditor.java
  * 将属性编辑器注册到spring中,参考如下:

<!--第一种,利用spring的注入把 日期样式也作为一个参数,更加灵活-->  
<
bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
 2   <property name="customEditors">
 3    <map>
 4     <entry key="java.util.Date">
 5      <bean class="com.bjsxt.spring.UtilDatePropertyEditor">
 6       <property name="format" value="yyyy-MM-dd"/>
 7      </bean>
 8     </entry>
 9    </map>
10   </property>
11  </bean> 

12 
 <!--第二种 -->
13  <!--
 
14 
 <bean id="utilDatePropertyEditor" class="com.bjsxt.spring.UtilDatePropertyEditor"></bean>
15   -->


java部分代码:

 1 /**
 2  * java.util.Date属性编辑器 
 3  * @author
 Administrator
 4 
 *
 5  */

 6 public class UtilDatePropertyEditor extends PropertyEditorSupport {
 7 

 8  private String format="yyyy-MM-dd";
 9 
 
10 
 @Override
11  public void setAsText(String text) throws
 IllegalArgumentException {
12   System.out.println("UtilDatePropertyEditor.saveAsText() -- text=" +
 text);
13 
  
14   SimpleDateFormat sdf = new
 SimpleDateFormat(format);
15   try
 {
16    Date d =
 sdf.parse(text);
17    this
.setValue(d);
18   } catch
 (ParseException e) {
19 
   e.printStackTrace();
20 
  }
21 
 }
22 

23  public void setFormat(String format) {
24   this.format =
 format;
25 
 }
26 

27 }
28
 
29 

posted on 2009-04-12 23:35 luofeng225 阅读(247) 评论(0)  编辑  收藏 所属分类: Spring


只有注册用户登录后才能发表评论。


网站导航:
 
<2009年4月>
2930311234
567891011
12131415161718
19202122232425
262728293012
3456789

导航

统计

公告

我曾经听到这么一个故事: 一个年轻的程序员问一个老程序员(一个比较牛逼的公司的CTO) 年轻程序员: 你为什么这么牛X., 就好像没有你不会的。老程序员: 积累的。年轻程序员: 怎么才能积累到您的程度呢。我每天都在积累。但是似乎都没有感觉到进步。老程序员: 我从20岁开始做到了一件事情,直到今天,而且尽可能地保证不间断。年轻程序员: 到底是什么? 老程序员: 我每天保证自己有2个小时在学习新的东西。

常用链接

留言簿(3)

随笔分类

随笔档案

文章分类

相册

收藏夹

Java Website

java技术博客

搜索

最新评论

阅读排行榜

评论排行榜