zoukankan      html  css  js  c++  java
  • 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>

     

  • 相关阅读:
    Ubuntu16.04更新源后apt-get update报错的解决方法
    安装Ubuntu16.04 64bit系统时出错的解决方案
    采用Python-Qt5制作置顶透明桌面提醒词/座右铭/便签
    如何手动解析Keras等框架保存的HDF5格式的权重文件
    读取yml配置文件中的值
    添加20位随机数,不重复,可以用来作为发票申请流水等功能
    java 从json串中取出某个字段的值
    Spring事务的两种方式
    (附表设计)超级全面的权限系统设计方案
    nfs 测试
  • 原文地址:https://www.cnblogs.com/wade-luffy/p/6072830.html
Copyright © 2011-2022 走看看