当我们利用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);
}
会产生如下的报错
这也印证了,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{ @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测试,发现成功转换了



