Spring--Spring类型转换

Posted jazon@

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring--Spring类型转换相关的知识,希望对你有一定的参考价值。

Spring类型转换的实现

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

使用场景

基于JavaBeans接口的类型转换

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

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

Spring内建PropertyEditor扩展

自定义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

统一类型转换服务

使用ConversionService作为依赖

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

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


以上是关于Spring--Spring类型转换的主要内容,如果未能解决你的问题,请参考以下文章

Spring -- Spring配置文件详解(Bean的依赖注入的数据类型(基本类型引用类型集合类型))

Spring - Spring 常用注解

Spring —— Spring简单的读取和存储对象 Ⅱ

Spring —— Spring Boot 配置文件

Spring-Boot + Spring-MVC + Thymeleaf + Apache Tiles

Spring -- Spring相关API (ApplicationContext getBean)