Spring 类型转换

  • Post author:
  • Post category:其他



https://docs.spring.io/spring-boot/docs/2.0.2.RELEASE/reference/htmlsingle/#boot-features-external-config-conversion

类型转换

spring boot 配置文件 application.properties 配置了一个日期,文件里的属性值只能是字符串,我们在配置类中定义的是Date类型,所以需要将字符串转换成Date类型。转换方式有两种,一种是使用PropertyEditor,另外一种是使用Converter

//application.properties
platform.version=1.0
platform.release=2018-05-25
//Platform.java
@ConfigurationProperties("platform")
@Component
public class Platform {

    private String version;

    private Date release;

    //getter and setter
}

PropertyEditor

针对上述案例,我们可以提供一个自定义的PropertyEditor。可以直接实现PropertyEditor接口,或更为常见的做法是继承PropertyEditorSupport,然后实现如下两个方法:

  • String getAsText()
  • void setAsText(String text)
public class CustomDateEditor extends PropertyEditorSupport {

    private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public String getAsText() {
        Date value = (Date)getValue();
        return dateFormat.format(value);
    }

    @Override
    public void setAsText(String text) throws IllegalArgumentException {
        try {
            setValue(dateFormat.parse(text));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }
}

定义了CustomDateEditor 后,spring是如何感知并使用这个转换器呢,可以通过CustomEditorConfigurer(继承自BeanFactoryPostProcessor)类,将CustomDateEditor注册到spring的BeanFactory中。CustomEditorConfigurer类说明中有两个使用xml配置的样例,我们这里使用对应的java注解配置方式。

第一种方式:通过

PropertyEditorRegistrar

注册,这也是推荐的方式。

@Configuration
public class Config {

    @Bean
    public CustomEditorConfigurer customEditorConfigurer() {
        CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
        customEditorConfigurer.setPropertyEditorRegistrars(new PropertyEditorRegistrar[]{new DatePropertyEditorRegistrar()});
        return customEditorConfigurer;
    }
}

public class DatePropertyEditorRegistrar implements PropertyEditorRegistrar {

    @Override
    public void registerCustomEditors(PropertyEditorRegistry registry) {
        registry.registerCustomEditor(Date.class, null, new CustomDateEditor());
    }
}

第二种方式:直接注册自定义的PropertiyEditor

@Configuration
public class Config {

    @Bean
    public CustomEditorConfigurer customEditorConfigurer() {
        CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();

        Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<>();
        customEditors.put(Date.class, CustomDateEditor.class);
        customEditorConfigurer.setCustomEditors(customEditors);
        return customEditorConfigurer;
    }   
}

Converter

使用Conveter进行类型转换,在spring boot中有两种使用方式,首先都需要创建一个实现Converter了接口类。

public class CustomDateConverter implements Converter<String, Date> {
    @Nullable
    @Override
    public Date convert(String source) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

第一种方式:使用

ConfigurationPropertiesBinding

注解。

@Component
@ConfigurationPropertiesBinding
public class CustomDateConverter implements Converter<String, Date> {
    @Nullable
    @Override
    public Date convert(String source) {
        try {
            return new SimpleDateFormat("yyyy-MM-dd").parse(source);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
}

第二种方式:配置名字为”conversionService”的bean。为什么是这个名字,可以参考类:org.springframework.boot.context.properties.ConversionServiceDeducer

@Configuration
public class Config {

    /**
     * {@link ConversionServiceDeducer}
     * @return
     */
    @Bean
    public ConversionService conversionService() {
        DefaultConversionService service = new DefaultConversionService();
        service.addConverter(new CustomDateConverter());
        return service;
    }
}



版权声明:本文为lilongjiu原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。