自定义类型转换器解决Spring配置文件注入类型错误的问题 PropertyEditorSupport

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创建的控制



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值