1 当我们进行bean注入到spring当中的时候,这个bean当中可能会存在着一些特殊类型的数据元素,如Date类型,当我们不进行一些特殊处理的时候,想直接给其赋值就会报告错误。
我们定义了如下类
- package com.japie.customproperty;
- import java.util.Date;
- /**
- * 自定义属性配置
- * @author Japie
- * 下午06:15:04
- */
- public class BoyMan {
- private Date birthDay;
- private String username;
- public BoyMan() {
- }
- public Date getBirthDay() {
- return birthDay;
- }
- public void setBirthDay(Date birthDay) {
- this.birthDay = birthDay;
- }
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- @Override
- public String toString()
- {
- return "BoyMan:["+username+this.birthDay+"]";
- }
- public static void main(String[] args) {
- }
- }
配置文件为
- <bean id="boyMan" class="com.japie.customproperty.BoyMan">
- <property name="birthDay" value="2011-06-17">
- <property name="username" value="japie"/>
- </bean>
当进行测试的时候报告如下的错误。
- Caused by: org.springframework.beans.TypeMismatchException:
- Failed to convert property value of type [java.lang.String] to
- required type [java.util.Date] for property 'birthDay';
2 那么如何解决上面的问题呢,有如下几种方法供参考
Declare a dateFormat bean, in “customer” bean, reference “dateFormat” bean as a factory bean. The factory method will call SimpleDateFormat.parse()
to convert String into Date object automatically.
1) 定义一个dateFormat bean,而后通而后通过工程模式在boyman这个类当中用构造器的模式进行引用,其实就是调用SimpleDateFormat.parse() 的方法,配置文件如下
- <bean id="boyMan" class="com.japie.customproperty.BoyMan">
- <property name="birthDay">
- <bean factory-bean="dateFormat" factory-method="parse">
- <constructor-arg value="2011-06-17" />
- </bean>
- </property>
- <property name="username" value="japie"/>
- </bean>
如此就可以进行正常的赋值了。
2)自定义日期熟悉编辑器
- <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>
3』通过重写spring的熟悉方法来实现代码如下
- package com.japie.injection;
- import java.beans.PropertyEditorSupport;
- import java.text.ParseException;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- /**
- * java.util.Date属性编辑器
- * @author japie
- *
- */
- public class UtilDatePropertyEditor extends PropertyEditorSupport {
- private String pattern;
- @Override
- public void setAsText(String text) throws IllegalArgumentException {
- System.out.println("---UtilDatePropertyEditor.setAsText()--->" + text);
- try {
- Date date = new SimpleDateFormat(pattern).parse(text);
- this.setValue(date);
- } catch (ParseException e) {
- e.printStackTrace();
- throw new IllegalArgumentException(text);
- }
- }
- public void setPattern(String pattern) {
- this.pattern = pattern;
- }
- }
以及在我们具体的bean当中引用其的配置
- <bean id="boyMan" class="com.japie.customproperty.BoyMan">
- <property name="birthDay" value="2011-06-17" />
- <property name="username" value="japie"/>
- </bean>