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>

 

原文地址:https://www.cnblogs.com/wade-luffy/p/6072830.html