spring如何注入Date类型的属性

spring可以为属性注入基本类型的值,也可以注入一个bean。当想注入非基本类型的值就得用到属性编辑器。它一般用在类型无法识别,如日期等。

实现步骤为以下两步:

1)继承PropertyEditorSupport

2)重写其setAsText方法,text是配置文件中的值(也就是为bean注入的值),我们就是将这个text按照需求进行转换。

先看下没用属性编辑器的情况:

public class MyDate {
	private Date date;

	public Date getDate() {
		return date;
	}

	public void setDate(Date date) {
		this.date = date;
	}

	public static void main(String[] args) {
		ApplicationContext context = new FileSystemXmlApplicationContext(
				"classpath:com/pb/propertyeditor/applicationContext.xml");
		MyDate date = (MyDate) context.getBean("md");
		System.out.println(date.getDate());
	}
}

bean id="md" class="com.pb.propertyeditor.MyDate">
<property name="date">
<value>2011-1-1</value>
</property>
</bean>

发生异常:

Caused by: java.lang.IllegalArgumentException: Cannot convert value of type [java.lang.String] to required type [java.util.Date] for property 'date': no matching editors or conversion strategy found

发生异常,没有发现匹配的编辑器或转换器。


现在需要的就是定义一个属性编辑器,并在spring中加入

public class CustomerProperty extends PropertyEditorSupport {
	String format;

	public String getFormat() {
		return format;
	}

	public void setFormat(String format) {
		this.format = format;
	}

	// text为需要转换的值,当为bean注入的类型与编辑器转换的类型匹配时就会交给setAsText方法处理
	public void setAsText(String text) throws IllegalArgumentException {
		SimpleDateFormat sdf = new SimpleDateFormat(format);
		try {
			this.setValue(sdf.parse(text));
		} catch (ParseException e) {
			e.printStackTrace();
		}
	}
}
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">   <!--配置一个自定义编辑器-->
		<property name="customEditors">		<!--需要编辑的属性类型,是一个map-->
			<map>
				<entry key="java.util.Date">
					<bean class="com.pb.propertyeditor.CustomerProperty">
						<property name="format" value="yyyy-mm-dd" />  <!--注入需要转换的格式-->
					</bean>
				</entry>
			</map>
		</property>
	</bean>

	<bean id="md" class="com.pb.propertyeditor.MyDate">
		<property name="date">
			<value>2011-1-1</value>
		</property>
	</bean>

输出结果:Sat Jan 01 00:01:00 CST 2011

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值