当我们利用Spring工厂对一个Java对象进行注入的时候,如果对象的属性为基本类型或者字符串类型(均被Spring识别为字符串类型),Spring自动帮助我们进行类型转换,
底层调用Integer.parseInt(""),其他类型同理,这很方便,但当Java对象中的属性为类似Date(非规定的\格式,而是-格式)时,Spring没有提供对应的转换方式,此时如果像上述方式进行注入就会报错。
@Test
public void test16(){
ApplicationContext ctx = new ClassPathXmlApplicationContext("/applicationContext.xml");
Person person = (Person) ctx.getBean("person");
System.out.println("person = " + person);
}
<bean id="person" class="com.qcby.converter.Person">
<property name="name" value="zzzz"></property>
<property name="birthday" value="2020-04-01"></property>
</bean>
会产生如下的报错
这也印证了,Spring是从String类型开始向别的类型转换的,此时我们就会用到自定义类型转换器来完成转换
package com.qcby.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateConverter implements Converter<String,Date> {
/*
* convert方法作用:String ---> Date
* SimpleDateFormat sdf = new SimpleDateFormat();
* sdf.parset(String) ---> Date
* parameter: source 代表的是配置文件中 日期字符串 value="2020-04-01"
*
* return : 当把转换好的Date作为convert方法的返回值后,Spring自动的为birthday属性进行注入(赋值)
* */
@Override
public Date convert(String source) {
Date date = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-mm-dd");
date = sdf.parse(source);
} catch (ParseException e) {
e.printStackTrace();
}
return date;
}
}
完成代码后,需要告知Spring,即进行注册
此时,再执行Test测试,发现成功转换了