读书人

Spring收拾3 - 自定义属性编辑器

发布时间: 2012-10-09 10:21:45 作者: rapoo

Spring整理3 -- 自定义属性编辑器

在我们注入属性时,遇到是日期类型,如果按普通属性去注入,则会报错,那我们该怎么解决?解决办法:自定义属性编辑器。

什么是属性编辑器,作用?

自定义属性编辑器,spring配置文件中的字符串转换成相应的对象进行注入spring已经有内置的属性编辑器,我们可以根据需求自己定义属性编辑器。

步骤:

1、? 定义一个属性编辑器必须继承java.beans.PropertyEditorSupport

2、? 在配置文件配置上我们定义的属性编辑器

下面我们来做一个java.util.Date属性编辑器,代码如下:

定义一个属性编辑器UtilDatePropertyEditor:

/** * java.util.Date属性编辑器  */public class UtilDatePropertyEditor extends PropertyEditorSupport {    private String format="yyyy-MM-dd";        @Override    public void setAsText(String text) throws IllegalArgumentException {       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;    }}

?配置文件applicationContext.xml

???

  <!-- 定义属性编辑器 -->          <bean id="customEditorConfigurer" value="yyyy-MM-dd"/>                  </bean>              </entry>           </map>       </property>    </bean>

??

以后我们就可以为java.util.Date进行注入,和普通属性一样使用,测试代码(略)

读书人网 >软件架构设计

热点推荐