1.场景
假设我们有一个Bean其中有一个属性为Date类型,我们通过配置文件配置其值为"2017-12-18" 注入到Spring的容器中后会报错
因为配置文件中的类型都默认为 String类型,而Bean中的类型为Date类型,因而直接注入会报错
这时可以通过实现自己的属性转化策略来实现从BeanDefinied转成Bean时进行一些附加的处理来帮助我们将String类型日期转化为Date并注入到容器
2.代码
a.Bean 如下:
public class Customer {
@Value("${data.Test}")
Date date;
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
@Override
public String toString() {
return "Customer{" +
"date=" + date +
'}';
}
}
b.配置文件如下:
data.Test=2017-09-25
c.定义自己的属性转化逻辑
public class MyDatePropertyEditor extends PropertyEditorSupport {
private String format="yyyy-MM-dd";
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
/**
* 此处的text就是从配置文件中获取的data.Test=2017-09-25中的2017-09-25
*/
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
this.setValue(sdf.parse(text));
} catch (ParseException e) {
e.printStackTrace();
}
}
}
d.将MyDatePropertyEditor 注入到容器
@Bean
public MyDatePropertyEditor myDatePropertyEditor(){
MyDatePropertyEditor myDatePropertyEditor=new MyDatePropertyEditor();
return myDatePropertyEditor;
}
e.将MyDatePropertyEditor 注册到CustomEditorConfigurer中
@Bean
public CustomEditorConfigurer customEditorConfigurer(){
CustomEditorConfigurer customEditorConfigurer=new CustomEditorConfigurer();
Map<Class<?>, Class<? extends PropertyEditor>> customEditors =new HashMap<>(1);
/**
* 注意此处的myDatePropertyEditor().getClass()
* 导致 MyDatePropertyEditor 中的属性需要写死 private String format="yyyy-MM-dd";
* 目前没有找打其它的办法。
*/
customEditors.put(java.util.Date.class,myDatePropertyEditor().getClass());
customEditorConfigurer.setCustomEditors(customEditors);
return customEditorConfigurer;
}
f.将定义的bean注入到容器
@Bean
public Customer customer(){
Customer o=new Customer();
return o;
}
g.编写controller测试
@ResponseBody
@RequestMapping("h2")
public Object test(){
System.out.println(customer.toString());
return "1";
}
注:后期将把bean的初始化过程整理一遍,以加深对Bean创建的控制