Spring 数据类型转换
数据类型转换:将一个数据对象转换成另一个数据对象
Spring提供了三种最常见的数据类型转换器PropertyEditor、Formatter、Converter
PropertyEditor
PropertyEditor是JDK自带的类型转换接口。主要用于实现String到其他类型的转换。Spring已经提供了用于常见类型转换的PropertyEditor实现。
PropertyEditorSupport
将字符串转换成LocalDateTime
public class CustomDatePropertyEditor extends PropertyEditorSupport {
private String formatter = "yyyy-MM-dd HH:mm:ss";
@Override
public void setAsText(String text) throws IllegalArgumentException {
LocalDateTime parse = LocalDateTime.parse(text, DateTimeFormatter.ofPattern(formatter));
System.out.println("-----LocalDateTimeEditor-----");
//转换后的值设置给PropertyEditorSupport内部的value属性
setValue(parse);
}
}
@Component
class TestDate {
@Value("2022-11-13 12:06:00")
private LocalDateTime dateTime;
public LocalDateTime getDateTime() {
return dateTime;
}
}
启动类
@ComponentScan("com.hc.annotation.converter")
public class AnnotationApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AnnotationApplication.class);
TestDate testDate = context.getBean("testDate", TestDate.class);
System.out.println(testDate.getDate()); // 控制台 2021-01-05T12:00
}
@Bean
public CustomEditorConfigurer customEditorConfigurer(){
CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
Map<Class<?>, Class<? extends PropertyEditor>> customEditors = new HashMap<Class<?>, Class<? extends PropertyEditor>>(6);
customEditors.put(LocalDateTime.class, CustomDatePropertyEditor.class);
customEditorConfigurer.setCustomEditors(customEditors);
return customEditorConfigurer;
}
}
PropertyEditorRegistrar
public class CustomPropertyEditorRegistrar implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry propertyEditorRegistry) {
// 将字符串格式为 yyyy年MM月dd日 的转换为 LocalDate
propertyEditorRegistry.registerCustomEditor(
LocalDate.class,
new CustomLocalDatePropertyEditor("yyyy年MM月dd日"));
}
}
class CustomLocalDatePropertyEditor extends PropertyEditorSupport {
private String formatter;
@Override
public void setAsText(String text) throws IllegalArgumentException {
LocalDate parse = LocalDate.parse(text, DateTimeFormatter.ofPattern(formatter));
System.out.println("-----LocalDateEditor-----");
//转换后的值设置给PropertyEditorSupport内部的value属性
setValue(parse);
}
public CustomLocalDatePropertyEditor(String formatter){
this.formatter = formatter;
}
}
@Component
class TestDate {
@Value("2022年11月13日")
private LocalDate date;
public LocalDate getDate() {
return date;
}
}
启动类
@ComponentScan("com.hc.annotation.converter")
public class AnnotationApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AnnotationApplication.class);
TestDate testDate = context.getBean("testDate", TestDate.class);
System.out.println(testDate.getDate()); // 控制台 2022-11-13
}
@Bean
public CustomEditorConfigurer customEditorConfigurer(){
CustomEditorConfigurer customEditorConfigurer = new CustomEditorConfigurer();
customEditorConfigurer.setPropertyEditorRegistrars(new PropertyEditorRegistrar[] {new CustomPropertyEditorRegistrar()});
return customEditorConfigurer;
}
}
Formatter
Formatter是Spring 3.0时提供的接口,只能转换String到其他类型,支持SPI机制。通常对于Spring MVC的参数绑定时的类型转换使用Formatter就可以了。Spring已经提供了用于常见类型转换的Formatter实现。
Converter
Converter是Spring 3.0时提供的接口,可以提供从一个对象类型到另一个对象类型的转换,支持SPI机制,当需要实现通用类型转换逻辑时应该使用Converter。Spring已经提供了用于常见类型转换的Converter实现。
/**
* 将 S 类型的源对象转换为目标类型 T 对象
*/
@FunctionalInterface
public interface Converter<S, T> {
@Nullable
T convert(S var1);
default <U> Converter<S, U> andThen(Converter<? super T, ? extends U> after) {
Assert.notNull(after, "After Converter must not be null");
return (s) -> {
T initialResult = this.convert(s);
return initialResult != null ? after.convert(initialResult) : null;
};
}
}
使用
public class String2IntegerConverter implements Converter<String, Integer> {
@Override
public Integer convert(String s) {
return Integer.valueOf(s) * 10; // 为了区分String和Integer能直接转换,使用翻十倍返回结果
}
}
@Component
class String2IntegerDataConverterTest {
// 注意这里使用的是 10,应该转为 10,但是我们转换的时候让他翻了10倍,所以他现在应该是 100
@Value("10")
public Integer ten;
public Integer getTen() {
return ten;
}
}
启动类
@ComponentScan("com.hc.annotation.data_converter.converter")
public class AnnotationApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AnnotationApplication.class);
String2IntegerDataConverterTest integerDataConverterTest = context.getBean("string2IntegerDataConverterTest", String2IntegerDataConverterTest.class);
System.out.println(integerDataConverterTest.getTen()); // 控制台 100
}
@Bean
public ConversionService conversionService(){
DefaultFormattingConversionService conversionService = new DefaultFormattingConversionService();
conversionService.addConverter(new String2IntegerConverter());
return conversionService;
}
}
详情看这篇文章,这里讲得很细 Spring数据类型转换机制全解