Spring 数据类型转换

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数据类型转换机制全解

或者官网 spring.io/spring-framework/docs/core.html#validation

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值