• Spring的属性编辑器


    bean类

    import java.util.Date;  
      
    public class Bean {  
        private Date date;  
        public Date getDate()  
        {  
            return date;  
        }  
        public void setDate(Date date)  
        {  
            this.date = date;  
        }  
    }  

    配置xml

    <bean id="bean" class="com.spring.bean.Bean">  
        <property name="date" value="2009-11-21"/>  
    </bean>  

    spring不能将string转换成date类型,没有匹配的编辑器或者转换机制。如果想实现string转换成Date,有两种解决办法。

    使用自定义属性编辑器

    import java.beans.PropertyEditorSupport;  
    import java.text.SimpleDateFormat;  
    import java.util.Date;    
    public class DatePropertyEditor extends PropertyEditorSupport  
    {  
       String format; @Override
    public void setAsText(String text) throws IllegalArgumentException { try { SimpleDateFormat sdf=new SimpleDateFormat(format);
           Date date
    =sdf.parse(text); this.setValue(date); //把转换后的值传过去 } catch (Exception e) { e.printStackTrace(); } } }

    写完编辑器后还需要把编辑器注入到spring中。 

        <bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">  
            <!-- 把值注入到CustomEditorConfigurer的 Map类型的customEditors属性-->  
            <property name="customEditors">  
                <map>  
                    <entry key="java.util.Date">  
                        <!-- 内部bean只供自己使用 -->  
                        <bean class="com.spring.util.DatePropertyEditor">
                  <property name="format" value="yyyy/MM/dd"></property>
                </bean>
    </entry> </map> </property> </bean>

    或者

    @InitBinder
    public void initBinder(WebDataBinder binder) {
      binder.registerCustomEditor(Date.class, "date", new DatePropertyEditor()); 
    }

    注册Spring自带的属性编辑器CustomDateEditor

    public class DatePropertyEditorRegistrar implements PropertyEditorRegistrar{
        public void registerCustomEditors(PropertyEditorRegistry registry) {
            registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"),true));
        }
    }

    通过在配置文件中将自定义的DatePropertyEditorRegistrar注册进入org.Springframework.beans.factory.config.CustomEditorConfigurer的propertyEditorRegistrars属性中

      <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
            <property name="propertyEditorRegistrars">
                <list>
                    <ref bean="datePropertyEditorRegistrar"/>
                </list>
            </property>
        </bean>

     

  • 相关阅读:
    pid系统控制算法
    pandas+numpy 对df数据中的某列进行等分分桶操作
    pandas学习
    angular6 数组遍历项进行双向绑定 丢失焦点 问题解决
    TypeScript 之构造器 constructor 方法 methods
    公开便民信息网站收集
    C++11_线程池
    百度网盘信息
    【赵强老师】MongoDB中的索引(下)
    TDSQL 4001 备份故障处理案例
  • 原文地址:https://www.cnblogs.com/wade-luffy/p/6072830.html
Copyright © 2020-2023  润新知