Spring注入日期到bean属性-CustomDateEditor

解决办法

在Spring中,可以通过两种方式注入日期:

  1. Factory bean

    声明一个dateFormat bean,在“customer” Bean,引用 “dateFormat” bean作为一个工厂bean。该工厂方法将调用SimpleDateFormat.parse()自动转换成字符串Date对象。

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="dateFormat" class="java.text.SimpleDateFormat">
		<constructor-arg value="yyyy-MM-dd" />
	</bean>

	<bean id="customer" class="com.yiibai.common.Customer">
		<property name="date">
			<bean factory-bean="dateFormat" factory-method="parse">
				<constructor-arg value="2015-12-31" />
			</bean>
		</property>
	</bean>

</beans>
  1. CustomDateEditor

声明一个 CustomDateEditor 类将字符串转换成 java.util.Date。

<bean id="dateEditor"
	   class="org.springframework.beans.propertyeditors.CustomDateEditor">
	
		<constructor-arg>
			<bean class="java.text.SimpleDateFormat">
				<constructor-arg value="yyyy-MM-dd" />
			</bean>
		</constructor-arg>
		<constructor-arg value="true" />
	</bean>

并声明另一个“CustomEditorConfigurer”,使 Spring转换 bean 属性,其类型为java.util.Date。

<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date">
					<ref local="dateEditor" />
				</entry>
			</map>
		</property>
	</bean>

bean配置文件的完整例子(applicationContext.xml)。

	
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="dateEditor"
		class="org.springframework.beans.propertyeditors.CustomDateEditor">

		<constructor-arg>
			<bean class="java.text.SimpleDateFormat">
				<constructor-arg value="yyyy-MM-dd" />
			</bean>
		</constructor-arg>
		<constructor-arg value="true" />

	</bean>

	<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
		<property name="customEditors">
			<map>
				<entry key="java.util.Date">
					<ref local="dateEditor" />
				</entry>
			</map>
		</property>
	</bean>

	<bean id="customer" class="com.yiibai.common.Customer">
		<property name="date" value="2015-12-31" />
	</bean>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值