zoukankan      html  css  js  c++  java
  • 自定义属性编辑器

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

    /**
     * java.util.Date属性编辑器
     * @author Administrator
     *
     */
    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>

  • 相关阅读:
    寒假练习集中贴
    7-49 打印学生选课清单 (25分)
    7-47 打印选课学生名单 (25分)
    进阶实验5-3.3 基于词频的文件相似度 (30分)-哈希
    进阶实验5-3.4 迷你搜索引擎 (35分)-哈希
    7-24 树种统计 (25分)-二叉排序树or快速排序
    7-25 朋友圈 (25分)-并查集
    进阶实验6-3.4 拯救007(升级版) (30分)-BFS
    基础实验6-2.3 拯救007 (25分)-DFS
    进阶实验4-3.5 哈夫曼编码 (30分)-最优二叉树
  • 原文地址:https://www.cnblogs.com/moonfans/p/2734861.html
Copyright © 2011-2022 走看看