spring type conversion system(类型转换系统)——概述

springFramework的类型转换机制代码位于spring-core.jar(spring3.0.5为例)下的org.springframework.core.convert包。

由上面的构件图可知,spring的convert系统大致由ConversionSerivce接口、converter包、support包三部分组成。(1)ConversionService接口直接就位于org.springframework.core.convert包下,是整个convert系统的入口,定义了如下方法:

      boolean canConvert(Class<?> sourceType, Class<?> targetType);

  <T> T convert(Object source, Class<T> targetType);

  boolean canConvert(TypeDescriptor sourceType, TypeDescriptor targetType);

  Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType);

     在org.springframework.core.convert包下还包括了几个异常类ConversionException、ConversionFailedException、ConverterNotFoundException

     此外还包括一个描述类型的类TypeDescriptor

(2) org.springframework.core.convert.converter包,是convert系统用到的各类Converters的SPI 实现。这里提到的SPI这里有必要简单介绍一下,

SPI的全名为Service Provider Interface.普通开发人员可能不熟悉,因为这个是针对厂商或者插件的。在java.util.ServiceLoader的文档里有比较详细的介绍。究其思想,其实是和"Callback"差不多。“Callback”的思想是在我们调用API的时候,我们可以自己写一段逻辑代码,传入到API里面,API内部在合适的时候会调用它,从而实现某种程度的“定制”。

下面回到正题,先看一下converter包中的接口关系图:

(3)org.springframework.core.convert.support包下则是对converter包下和convert包下各类接口的默认实现

原文地址:https://www.cnblogs.com/hzhuxin/p/2327579.html