Spring(十二)--Spring类型转换

本文详细介绍了Spring中类型转换的实现,包括基于JavaBeans接口的类型转换、Spring内建和自定义PropertyEditor扩展,Spring3的GenericConverter接口及其优化,以及如何扩展Spring类型转换器。同时阐述了ConversionService作为统一类型转换服务的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Spring类型转换的实现

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

使用场景

image.png

基于JavaBeans接口的类型转换

  • 核心职责: 将String类型的内容转换为目标类型的对象
  • 扩展原理

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

Spring内建PropertyEditor扩展

image.png

自定义PropertyEditor扩展

  • 扩展模式

1.扩展java.beans.PropertyEditorSupport类

  • 实现org.springframework.beans.PropertyEditorRegistrar

1.实现registerCustomEditors(org.springframework.beans.PropertyEditorRegistry)方法
2.将PropertyEditorRegistrar实现注册为SpringBean

  • 向org.springframework.beans.PropertyEditorRegistry注册自定义PropertyEditor实现

1.通用类型实现registerCustomEditor(Class<?>, PropertyEditor)
2.Java Bean属性类型实现:registerCustomEditor(Class<?>, String, PropertyEditor)

Spring3通用类型转换接口

  • 类型转换接口
@FunctionalInterface
public interface Converter<S, T> {
	@Nullable
	T convert(S source);
}
  • 通用类型转换接口
org.springframework.core.conert.converter.GenericConverter
核心方法: convert(Object, TypeDescriptor. TypeDescriptor)
配对类型: org.springframework.core.convert.converter.GenericConverter.ConvertiblePair 
类型描述: org.springframework.core.convert.TypeDescriptor

GenericConverter接口

使用场景:用于"复合"类型转换场景,比如Collection, Map数组等
转换范围: Set getConvertibleTypes()
配对类型:org.springframework.core.convert.converter.GenericConverter.ConvertiblePair
转换方法:convert(Object, TypeDescriptor, TypeDescriptor)
类型描述: org.springframework.core.convert.TypeDescriptor

优化GenericConverter接口

增加sourceType和TargetType前置判断,类型条件判断: ConditionalGenericConverter

public interface ConditionalConverter {

	boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType);
}

扩展Spring类型转换器

  • 实现转换器接口,任一即可

1.org.sringframework.core.convert.convert.converter
2.org.springframework.core.convert.converter.ConverterFactory
3.org.springframework.core.convert.converter.GenericConerter

  • 注册转换器实现

1.通过ConversionServiceFactoryBean SpringBean
2.通过org.springframework.core.convert.ConversionService API

统一类型转换服务

image.png

使用ConversionService作为依赖

类型转换底层接口-org.springframework.beans.TypeConverter,Spring直接使用此接口实现作为转换实现。

  • 核心方法:convertIfNecessary重载方法
  • 抽象实现:org.springframework.beans.TypeConverterSupport
  • 简单实现: org.springframework.beans.SimpleTypeConverter

image.png
image.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值