Spring 类型转换、数值绑定与验证(二)—PropertyEditor与Conversion

本文主要是介绍Spring 类型转换、数值绑定与验证(二)—PropertyEditor与Conversion,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

 Spring 中,属性类型转换是在将数值绑定到目标对象时完成的。例如在创建ApplicationContext 容器时,将XML配置的bean 转换成Java类型对象,主要是借助了PropertyEditor类,而在Spring MVC 的Controller的请求参数转化为特定类型时,我们也可以自定义转化器Convert并注册来完成转换。以下是Spring相关源码分析。

1 PropertyEditor

JDK自带的接口。支持各种不同的方式来显示和更新特性值。
xml 配置Bean 或者@Value 赋值到Bean的时候,属性字段值很多是文本类型的字符串,但是属性的类型却可能是Integer,File等类型,PropertyEditor 就是用来把文本型的值转换为对应类型值的工具。 其关键方法是void setAsTest(String text)。

PropertyEditorSupport 是JDK提供的默认自定义,各种自定义的PropertyEditor大多是继承该类来实现。重写setAsText方法。

1.1 PropertyEditorRegistry

PropertyEditor 注册表,提供了用于注册并管理PropertyEditor的接口。

PropertyEditorRegistrySupport 是其默认实现,创建并注册了一些默认的PropertyEditor,并增加了对类型转换Convertion的支持。

图 PropertyEditorRegistrySupport UML

defaultEditors 及 customEditors 分别用来存储注册的默认及自定义editors。而overriddenDefaultEditors 是用来存储覆盖默认的editors。对应方法为overrideDefaultEditor。

public void overrideDefaultEditor(Class<?> requiredType, PropertyEditor propertyEditor) {if (this.overriddenDefaultEditors == null) {this.overriddenDefaultEditors = new HashMap<>();}this.overriddenDefaultEditors.put(requiredType, propertyEditor);
}

注册器的类型编辑器覆盖顺序为: 自定义editors -> ConversionService -> 覆盖默认editors -> 默认editors。 defaultEditors 最先被覆盖。boolean类型遍历configValueEditorsActive 用来控制在创建默认editors时,是否需要创建用于配置的editor(这类editor通常不适合用于数据绑定)。

图 createDefaultEditors 方法的部分截图

customEditorsForPath 是用来存储为特定属性路径注册的editor。

图 registerCustomEditor 方法

1.2 PropertyEditorRegistrar

PropertyEditor 注册器,用于把editors 注册到给定的registry中。

ResourceEditorRegistrar 是其默认实现。通常在Spring容器初始化时被调用。

图 ResourceEditorRegistrar UML

1.3 CustomEditorConfigurer

用于注册自定义Editor。可以在XML 或者使用注册来创建这个bean,并设置自定义editor属性。

图 CustomEditorConfigurer UML

<bean id="customEditorConfigurer" class="org.springframework.beans.factory.config.CustomEditorConfigurer"> <!-- 设置 customEditors 属性 --> <property name="customEditors"> <map> <!-- 注册自定义的日期编辑器 --> <entry key="java.util.Date"> <bean class="org.springframework.beans.propertyeditors.CustomDateEditor"> <!-- 设置日期格式 --> <constructor-arg value="yyyy-MM-dd"/> <!-- 设置是否允许空值 --> <constructor-arg value="false"/> </bean> </entry> <!-- 可以添加更多的自定义编辑器 --> </map> </property> </bean> 

2 Conversion

可以替代PropertyEditor,主要用于在绑定数值时,将源类型转换为目标类型。

Spring 定义的Converter<S,T>接口,只定义了一个方法:

T convert(S source); // 将源类型转换为目标类型。

ConverterFactory<S,R> 接口,定义了一个工厂方法用于创建Converter实例:

<T extends R> Converter<S, T> getConverter(Class<T> targetType);

2.1 GenericConverter

支持在多个不同的源类型和目标类型之间进行转换。使用场景有:将不同类型的数值转换为集合,或者根据字段上的注解或泛型信息来驱动类型转换。

图 GenericConverter接口 UML

ConveriblePair 保存源类型及目标类型。

getConvertibleTypes 返回可以被转换的类型对(源类型与目标类型)。

ConditionalConverter 用于判断源类型是否可以转换的接口。

public interface ConditionalConverter {boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType);
}

以下是Spring内部实现了GenericConverter及ConditionalConverter 的接口的ArrayToCollectionConverter(内部类,不对外部使用)源代码:

final class ArrayToCollectionConverter implements ConditionalGenericConverter {private final ConversionService conversionService;public ArrayToCollectionConverter(ConversionService conversionService) {this.conversionService = conversionService;}@Overridepublic Set<ConvertiblePair> getConvertibleTypes() {return Collections.singleton(new ConvertiblePair(Object[].class, Collection.class));}@Overridepublic boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {return ConversionUtils.canConvertElements(sourceType.getElementTypeDescriptor(), targetType.getElementTypeDescriptor(), this.conversionService);}@Override@Nullablepublic Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {if (source == null) {return null;}int length = Array.getLength(source);TypeDescriptor elementDesc = targetType.getElementTypeDescriptor();Collection<Object> target = CollectionFactory.createCollection(targetType.getType(),(elementDesc != null ? elementDesc.getType() : null), length);if (elementDesc == null) {for (int i = 0; i < length; i++) {Object sourceElement = Array.get(source, i);target.add(sourceElement);}}else {for (int i = 0; i < length; i++) {Object sourceElement = Array.get(source, i);Object targetElement = this.conversionService.convert(sourceElement,sourceType.elementTypeDescriptor(sourceElement), elementDesc);target.add(targetElement);}}return target;}}

2.2 ConversionService 与 ConverterRegistry

ConversionService定义了在运行期间执行转换的统一接口。

ConversionRegistry  Converter注册器,定义了用于添加/删除转换器的方法。

GenericConversionService 同时实现了这两个接口。而DefaultConversionService 继承了这个类,并增加了两个静态方法:

getSharedInstance(): 创建一个共享的DefaultConversionServices单例。

addDefaultConverters(ConverterRegistry converterRegistry):创建并注册一些默认的转换器。

2.3 ConversionServiceFactoryBean

用于添加自定义转换器的Bean。

<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean"> <!-- 在这里配置你的类型转换器 --> <property name="converters"> <list> <bean class="com.example.MyCustomConverter"/> <!-- 其他转换器 --> </list> </property> </bean>

其源代码如下:

public class ConversionServiceFactoryBean implements FactoryBean<ConversionService>, InitializingBean {@Nullableprivate Set<?> converters;@Nullableprivate GenericConversionService conversionService;/*** Configure the set of custom converter objects that should be added:* implementing {@link org.springframework.core.convert.converter.Converter},* {@link org.springframework.core.convert.converter.ConverterFactory},* or {@link org.springframework.core.convert.converter.GenericConverter}.*/public void setConverters(Set<?> converters) {this.converters = converters;}@Overridepublic void afterPropertiesSet() {this.conversionService = createConversionService();ConversionServiceFactory.registerConverters(this.converters, this.conversionService);}/*** Create the ConversionService instance returned by this factory bean.* <p>Creates a simple {@link GenericConversionService} instance by default.* Subclasses may override to customize the ConversionService instance that* gets created.*/protected GenericConversionService createConversionService() {return new DefaultConversionService();}// implementing FactoryBean@Override@Nullablepublic ConversionService getObject() {return this.conversionService;}@Overridepublic Class<? extends ConversionService> getObjectType() {return GenericConversionService.class;}@Overridepublic boolean isSingleton() {return true;}}

这篇关于Spring 类型转换、数值绑定与验证(二)—PropertyEditor与Conversion的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/737720

相关文章

Java中流式并行操作parallelStream的原理和使用方法

《Java中流式并行操作parallelStream的原理和使用方法》本文详细介绍了Java中的并行流(parallelStream)的原理、正确使用方法以及在实际业务中的应用案例,并指出在使用并行流... 目录Java中流式并行操作parallelStream0. 问题的产生1. 什么是parallelS

Java中Redisson 的原理深度解析

《Java中Redisson的原理深度解析》Redisson是一个高性能的Redis客户端,它通过将Redis数据结构映射为Java对象和分布式对象,实现了在Java应用中方便地使用Redis,本文... 目录前言一、核心设计理念二、核心架构与通信层1. 基于 Netty 的异步非阻塞通信2. 编解码器三、

SpringBoot基于注解实现数据库字段回填的完整方案

《SpringBoot基于注解实现数据库字段回填的完整方案》这篇文章主要为大家详细介绍了SpringBoot如何基于注解实现数据库字段回填的相关方法,文中的示例代码讲解详细,感兴趣的小伙伴可以了解... 目录数据库表pom.XMLRelationFieldRelationFieldMapping基础的一些代

一篇文章彻底搞懂macOS如何决定java环境

《一篇文章彻底搞懂macOS如何决定java环境》MacOS作为一个功能强大的操作系统,为开发者提供了丰富的开发工具和框架,下面:本文主要介绍macOS如何决定java环境的相关资料,文中通过代码... 目录方法一:使用 which命令方法二:使用 Java_home工具(Apple 官方推荐)那问题来了,

Java HashMap的底层实现原理深度解析

《JavaHashMap的底层实现原理深度解析》HashMap基于数组+链表+红黑树结构,通过哈希算法和扩容机制优化性能,负载因子与树化阈值平衡效率,是Java开发必备的高效数据结构,本文给大家介绍... 目录一、概述:HashMap的宏观结构二、核心数据结构解析1. 数组(桶数组)2. 链表节点(Node

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

详解SpringBoot+Ehcache使用示例

《详解SpringBoot+Ehcache使用示例》本文介绍了SpringBoot中配置Ehcache、自定义get/set方式,并实际使用缓存的过程,文中通过示例代码介绍的非常详细,对大家的学习或者... 目录摘要概念内存与磁盘持久化存储:配置灵活性:编码示例引入依赖:配置ehcache.XML文件:配置

Java 虚拟线程的创建与使用深度解析

《Java虚拟线程的创建与使用深度解析》虚拟线程是Java19中以预览特性形式引入,Java21起正式发布的轻量级线程,本文给大家介绍Java虚拟线程的创建与使用,感兴趣的朋友一起看看吧... 目录一、虚拟线程简介1.1 什么是虚拟线程?1.2 为什么需要虚拟线程?二、虚拟线程与平台线程对比代码对比示例:三

Java中的.close()举例详解

《Java中的.close()举例详解》.close()方法只适用于通过window.open()打开的弹出窗口,对于浏览器的主窗口,如果没有得到用户允许是不能关闭的,:本文主要介绍Java中的.... 目录当你遇到以下三种情况时,一定要记得使用 .close():用法作用举例如何判断代码中的 input

Spring Gateway动态路由实现方案

《SpringGateway动态路由实现方案》本文主要介绍了SpringGateway动态路由实现方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随... 目录前沿何为路由RouteDefinitionRouteLocator工作流程动态路由实现尾巴前沿S