Spring CustomPropertyEditor

这篇文章主要介绍spring的自定义属性编辑器。一般地我们在xml配置文件中配置的属性值都是String类型的。如:

<bean id="userman" class="com.zsq.cn.test.bean.UserMan">
<property name="birthday" value="1994-09-13" />
</bean>

1994-09-13通过注入到bean里面后是字符串类型的,如果UserMan这个类中的birthday是Date类型的,Spring再启动的时候就会报错。为了将1994-09-13转化为日期类型,需要注册一个将字符串转换为Date类型的自定义属性编辑器。


需要说明的是 Spring以及实现了大部分的属性编辑器 比如 String 转为 int float double  URL class 等。当然你也可以使用Spring Type Convert 进行类与类(包括类与Stringl类)之间的转换来达到同样的效果,Convert的具体用法可以参照Spring 官方参考文档 的9.5章节


1 首先新建一个UserMan类

public class UserMan {
	
	private Date birthday;
	
	private User user;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public Date getBirthday() {
		return birthday;
	}

	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
}
2 新建两个自定义属性编辑器,一个用于将string转化为 Date 一个将string转化为User

public class DatePropertyEditor extends PropertyEditorSupport{
	
	private String dateFormat = "yyyy-mm-dd";//默认日期格式

	public void setDateFormat(String dateFormat){
		this.dateFormat = dateFormat;//重设日期格式
	}

	@Override
	public void setAsText(String stringDate){
		SimpleDateFormat sdFormat = new SimpleDateFormat(dateFormat);
		try {
			Date d = sdFormat.parse(stringDate);
			this.setValue(d);
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}


public class UserPropertyEditor extends PropertyEditorSupport {
	@Override
	public void setAsText(String str){ 
		User user = new User();
		user.setName("zsq");
		user.setPassword("zsq");
		setValue(user);
	}
}

3 在xml文件中注册bean 

<bean id="userman" class="com.zsq.cn.test.bean.UserMan">
		<property name="birthday" value="1994-09-13" />
		<property name="user" value="any Strig" />
	</bean>
4 在xml文件中注册两个自定义属性编辑器

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date" value="com.zsq.cn.common.sys.utils.DatePropertyEditor" />
			</map>
		</property>
	</bean>
	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="com.zsq.cn.common.entity.User" value="com.zsq.cn.common.sys.utils.UserPropertyEditor" />
			</map>
		</property>
	</bean>

5 运行结果:

UserMan us = ApplicationContextUtils.getBean("userman", UserMan.class);


birthday 的值是:

 Thu Jan 13 00:09:00 CST 1994













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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值