现在的位置: 首页 > 综合 > 正文

Spring自定义属性编辑器

2013年10月03日 ⁄ 综合 ⁄ 共 1918字 ⁄ 字号 评论关闭
 

什么是属性编辑器,作用?
 * 自定义属性编辑器,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>

抱歉!评论已关闭.