欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring boot 自定义配置文件的类型转换

程序员文章站 2022-06-14 15:30:48
...

配置文件

application.yml

myYml:
  date: 20101020

String To Date 转换

public  class StringToDateConverter implements Converter<String, Date> {
    public Date convert(String source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            return sdf.parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}

int To Date 转换

public  class IntegerToDateConverter implements Converter<Integer, Date> {
    public Date convert(Integer source) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            return sdf.parse(String.valueOf(source));
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }
}

注入类型转换bean

@Bean
public ConversionService conversionService() {
    ConversionServiceFactoryBean bean = new ConversionServiceFactoryBean();
    Set<Converter> converters = new HashSet<>();
    converters.add(new StringToDateConverter());
    converters.add(new IntegerToDateConverter());
    bean.setConverters(converters);
    bean.afterPropertiesSet();
    return bean.getObject();
}
相关标签: spring spring-boo