首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

Spring中自定义日期的变换

2013-08-04 
Spring中自定义日期的转换在Spring中,如何向bean中的注入符合格式的日期呢?看下面的例子:import java.util

Spring中自定义日期的转换
在Spring中,如何向bean中的注入符合格式的日期呢?看下面的例子:

import java.util.Date; public class Customer { Date date; public Date getDate() {return date;} public void setDate(Date date) {this.date = date;} @Overridepublic String toString() {return "Customer [date=" + 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="customer" value="2011-01-31" />
</bean>

</beans>
  这样注入是出錯的,报錯:

ApplicationContext context = new ClassPathXmlApplicationContext(
"SpringBeans.xml");

Customer cust = (Customer) context.getBean("customer");
System.out.println(cust);

Caused by: org.springframework.beans.TypeMismatchException:
Failed to convert property value of type [java.lang.String] to
required type [java.util.Date] for property 'date';

nested exception is 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

解决的方法有两个,一个是使用factory bean:
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beanshttp://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <bean id="dateFormat" /></bean> <bean id="customer" factory-method="parse"><constructor-arg value="2010-01-31" /></bean></property></bean> </beans>


另外的方法是使用CustomDateEditor,方法如下:
 
<bean id="dateEditor"/></bean></constructor-arg><constructor-arg value="true" /> </bean> <bean /></entry></map></property></bean> <bean id="customer" value="2010-02-31" /></bean> 

---------------------------------------------
讲解:
Spring 在装配Bean 时可以使用字符串装配其他数据类型,如URL。也就是说Spring 会自动的将String 类型转换成URL类型进行Bean 的属性装配。这是通过JavaBean API 实现的(java.beans.PropertyEditor 接口)。 那么如何通过Spring 配置将String 类型转换成自定义的类型呢?

      这首先需要写一个编辑器类,该类用于实现将String 类型转换成您需要的数据类型。这只需要继承JDK 中的 java.beans.PropertyEditorSupport 类来实现自己的编辑器类。然后我们只需要在Spring 的容器中对这个编辑器进行有效的“注册”便可以实现Spring 在装配Bean 时自动的将Strng 类型转换成我们自定义的类型。 这就是今天我要介绍的CustomEditorConfigurer 类用于实现在Spring 中注册自己定义的编辑器。它是Spring 当中一个非常有用的工厂后处理类(工厂后处理通过Spring 的BeanFactoryPostProcessor 接口实现, 它是在Spring 容器启动并初始化之后进行对Spring 容器的操作类)。在Spring 中已经注册了不少编辑器类,他们都用于String 类型转换为其他的数据类型,如URL,Date等。

热点排行