Spring自定义属性编辑器

Spring自定义属性编辑器

​ 关于Spring的属性编辑器的使用

public class Student {
    private Long id;
    private String name;
    private Date birthday;

    public Long getId() {
        return id;
    }
    public void setId(Long id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
}

此时如果用String类型的形式为birthday赋值,则需要用到属性编辑器做一个转换

<bean name="xiaoming2" id="student" class="com.yqs.base.Student">
    <property name="id" value="1"/>
    <property name="name" value="小明"/>
    <property name="birthday" value="2002.07.07"/>
</bean>
方式一:

​ 自定义属性编辑器,并将其注册到CustomEditorConfigurer的customEditors中

public class CustomerPropertyEditor extends PropertyEditorSupport {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM.dd");
    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        try {
            Date date = sdf.parse(text);
            this.setValue(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <!-- 把值注入到CustomEditorConfigurer的 Map类型的customEditors属性-->
    <property name="customEditors">
        <map>
            <entry key="java.util.Date" value="com.yqs.config.CustomerPropertyEditor"/>
        </map>
    </property>
</bean>
方式二:

​ 使用spring的PropertyEditorRegistrar,将自定义的属性编辑器注册到CustomEditorConfigurer的customEditors中

public class CustomerPropertyEditorRegistrar implements PropertyEditorRegistrar {
    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy.MM.dd"),true));
    }
}
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
    <property name="propertyEditorRegistrars">
        <list>
            <bean class="com.yqs.config.CustomerPropertyEditorRegistrar" />
        </list>
    </property>
</bean>
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容