spring 属性编辑器

介绍

在spring中可以把普通属性注入道对象中,但是Date类型就无法被识别。列如

public class User {

	private Date dateValue;

	public Date getDateValue() {
		return dateValue;
	}

	public void setDateValue(Date dateValue) {
		this.dateValue = dateValue;
	}

	public static void main(String[] args) {
		ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:application-propertyEdtior.xml");
		ctx.getBean(User.class);
	}
}


xml配置文件


	<bean id="user" class="com.property.User" >
		<property name="dateValue"><value>2019-06-13</value></property>

	</bean>

直接测试上面的main方法会抛出异常,因为User中dateValue中是Date类型,无法转换,为此Spring通过属性编译器来解决问题

自定义属性编辑器

通过继承java.beans.PropertyEditorSupport类,重写public void setAsText(String text) 方法,该类是jdk中方法。

代码如下

public class DatePropertyEditor extends PropertyEditorSupport {

    private String format = "yyyy-MM-dd";

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date date = null;
        try {
            date = sdf.parse(text);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        this.setValue(date);
    }
}

xml代码如下

	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date" value="com.property.DatePropertyEditor">
			<!-- 有的书上建议用bean,这里其实必须用value-->
				</entry>
			</map>
		</property>
	</bean>

此时再次执行上面的main方法,则可以正常执行

Spring自带编辑器

注册Spring自带的属性编辑器CustomDateEditor,
1.定义属性编辑器

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

org.springframework.beans.propertyeditors.CustomDateEditor ,Spring属性编辑器,其实查看源代码就可以得知,此方法和我们上面自己的方法是一样也是继承了PropertyEditorSupport 类

PropertyEditorRegistrar 通过该类注册到属性propertyEditorRegistrars ,这里的缓存其实就是Map

xml代码

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

此刻再次执行main方法会发现和之前一样的执行结果。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值