第十五章:Spring 类型转换

Spring 类型转换的实现

  • 基于 JavaBeans 接口的类型转换实现
  • 基于 java.beans.PropertyEditor 接口扩展
  • Spring 3.0+ 通用类型转换实现

使用场景

场景基于 JavaBeans 接口的类型转换实现
数据绑定YES
BeanWrapperYES
Bean 属性类型装换YES
外部化属性类型转换NO

基于 JavaBeans 接口的类型转换

核心职责

  • 将 String 类型的内容转化为目标类型的对象

扩展原理

  • Spring 框架将文本内容传递到 PropertyEditor 实现的 setAsText(String) 方法
  • PropertyEditor#setAsText(String) 方法实现将 String 类型转化为目标类型的对象
  • 将目标类型的对象传入 PropertyEditor#setValue(Object) 方法
  • PropertyEditor#setValue(Object) 方法实现需要临时存储传入对象
  • Spring 框架将通过 PropertyEditor#getValue() 获取类型转换后的对象

Spring 內建 PropertyEditor 扩展

转换场景实现类
String -> Byte 数组org.springframework.beans.propertyeditors.ByteArrayPropertyEditor
String -> Charorg.springframework.beans.propertyeditors.CharacterEditor
String -> Char 数组org.springframework.beans.propertyeditors.CharArrayPropertyEditor
String -> Charsetorg.springframework.beans.propertyeditors.CharsetEditor
String -> Classorg.springframework.beans.propertyeditors.ClassEditor
String -> Currencyorg.springframework.beans.propertyeditors.CurrencyEditor

自定义 PropertyEditor 扩展

扩展模式

  • 扩展 java.beans.PropertyEditorSupport 类
  • 实现 org.springframework.beans.PropertyEditorRegistrar
  • 实现 registerCustomEditors(org.springframework.beans.PropertyEditorRegistry) 方法
  • 将 PropertyEditorRegistrar 实现注册为 Spring Bean
  • 向 org.springframework.beans.PropertyEditorRegistry 注册自定义 PropertyEditor 实现
  • 通用类型实现 registerCustomEditor(Class<?>, PropertyEditor)
  • Java Bean 属性类型实现:registerCustomEditor(Class<?>, String, PropertyEditor)

Spring PropertyEditor 的设计缺陷

  • 违反职责单一原则 java.beans.PropertyEditor 接口职责太多,除了类型转换,还包括 - Java Beans 事件和 Java GUI 交互
  • java.beans.PropertyEditor 实现类型局限
  • 来源类型只能为 java.lang.String 类型
  • java.beans.PropertyEditor 实现缺少类型安全
  • 除了实现类命名可以表达语义,实现类无法感知目标转换类型

Spring 3 通用类型转换接口

  • 类型转换接口 - org.springframework.core.convert.converter.Converter<S,T>
  • 通用类型转换接口 - org.springframework.core.convert.converter.GenericConverter
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值