Spring类型转换(Converter)

Spring的类型转换

以前在面试中就有被问到关于spring数据绑定方面的问题,当时对它一直只是朦朦胧胧的概念,最近稍微闲下来有时间看了一下其中数据转换相关的内容,把相应的内容做个记录。

下面先说明如何去用,然后再放一下个人看参数绑定源码的一些笔记,可能由于实力不够,有些地方说的不是很正确,如果有纰漏还请各位指出。

ConversionService

原生的Java是有一个可以提供数据转换功能的工具——PropertyEditor。但是它的功能有限,它只能将字符串转换为一个Java对象。在web项目中,如果只看与前端交互的那一部分,这个功能的确已经足够了。但是在后台项目内部可就得重新想办法了。

Spring针对这个问题设计了Converter模块,它位于org.springframework.core.converter包中。该模块足以替代原生的PropertyEditor,但是spring选择了同时支持两者,在Spring MVC处理参数绑定时就用到了。

该模块的核心是ConversionService接口,内容如下:

public interface ConversionService {

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

    boolean canConvert(@Nullable TypeDescriptor sourceType, TypeDescriptor targetType);

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

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

}

接口里的方法定义的还是比较直观的,见名知意。其中的TypeDescriptor是spring自己定义的类,它提供了获取类型更多信息的便捷方法。比如是否含有注解、是否实现map接口、获取map的key与value的TypeDescriptor等等。

由此可见,converter模块不仅支持任意类型之间的转换,而且能更简单地获得更多的类型信息从而做出更细致的类型转换。

转换器

ConversionService只是个Service,对于每个类型转换的操作,它并不是最终的操作者,它会将相应操作交给对应类型的转换器。而在实际项目中,由于业务复杂,对类型转换的要求也不一样,因此spring提供了几个接口来方便自定义转换器。

Converter<S, T>

接口定义如下:

@FunctionalInterface
public interface Converter<S, T> {
    @Nullable
    T convert(S var1);
}

该接口非常简单,只定义了一个转换方法,两个泛型参数则是需要转换的两个类型。在单独处理两个类型的转换时这是首选,即一对一,但是倘若有同一父类(或接口)的类型需要进行类型转化,为每个类型都写一个Converter显然是十分不理智的。对于这种情况,spring提供了一个ConverterFactory接口。

ConverterFactory<S, R>

public interface ConverterFactory<S, R> {
    <T extends R> Converter<S, T> getConverter(Class<T> var1);
}

我们可以看到,该工厂方法可以生产从S类型到T类型的转换器,而T类型必定继承或实现R类型,我们可以形象地称为“一对多”,因此该接口更适合实现需要转换为同一类型的转换器。

对于大部分需求上面两个接口其实已经足够了(至少我感觉是),但是不是还没用到TypeDescriptor吗?如果要实现更为复杂的转换功能的话,spring提供了拥有TypeDescriptor参数的GenericConverter接口。

GenericConverter

public interface GenericConverter {
    
    @Nullable
    Set<ConvertiblePair> getConvertibleTypes();

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

    final class ConvertiblePair {

        private final Class<?> sourceType;

        private final Class<?> targetType;

        public ConvertiblePair(Class<?> sourceType, Class<?> targetType) {
            Assert.notNull(sourceType, "Source type must not be null");
            Assert.notNull(targetType, "Target type must not be null");
            this.sourceType = sourceType;
            this.targetType = targetType;
        }

        public Class<?> getSourceType() {
            return this.sourceType;
        }

        public Class<?> getTargetType() {
            return this.targetType;
        }
        
        // 省去了一些Override方法
    }
}

GenericConverter中拥有一个内部类ConvertiblePair,这个内部类的作用只是封装转换的源类型与目标类型。

对于GenericConvertergetConvertibleTypes方法就返回这个转换器支持的转换类型(一对一,一对多,多对多都可以满足),convert方法和以前一样是负责处理具体的转换逻辑。

而且,如果你觉得对于一个转换器来说只通过判断源类型和目标类型是否一致来决定是否支持转换还不够,Spring还提供了另一个接口ConditionalGenericConverter

ConditionalGenericConverter

public interface ConditionalConverter {

   boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType);

}

public interface ConditionalGenericConverter extends GenericConverter, ConditionalConverter {

}

ConditionalGenericConverter接口继承了GenericConverterConditionalConverter接口,在matches方法中就可以在源类型与目标类型已经匹配的基础上再进行判断是否支持转换。

Spring官方实现ConditionalGenericConverter接口的转换器大多用来处理有集合或数组参与的转换,这其中的matches方法就用来判断集合或数组中的元素是否能够成功转换。而且因为GenericConverterConditionalGenericConverter接口功能太类似,索性就直接实现ConditionalGenericConverter接口了。

如何使用

那么如何使用转换器呢,Spring要求我们要把所有需要使用转换器注册到ConversionService,这样Spring在遇到类型转换的情况时,会去ConversionService中寻找支持的转换器,进行必要的格式转换。

支持转换器注册的接口为ConverterRegistry

public interface ConverterRegistry {

    void addConverter(Converter<?, ?> converter);

    <S, T> void addConverter(Class<S> sourceType, Class<T> targetType, Converter<? super S, ? extends T> converter);

    void addConverter(GenericConverter converter);

    void addConverterFactory(ConverterFactory<?, ?> factory);

    void removeConvertible(Class<?> sourceType, Class<?> targetType);

}

但我们使用的是另一个继承了ConversionServiceConverterRegistry的接口ConfigurableConversionService,通过这个接口,就可以注册自定义的转换器了。

格式化

转换器提供的功能是一个类型到另一个类型的单向转换,而在web项目中,有些数据是需要经常做双向转换,最常见的就是日期时间了。将请求中一定格式的字符串转换为日期类型,而在返回的相应中将日期类型再做指定格式的格式化,Spring中提供的工具就是Formatter接口。

Formatter<T>

@FunctionalInterface
public interface Printer<T> {
    String print(T object, Locale locale);
}

@FunctionalInterface
public interface Parser<T> {
    T parse(String text, Locale locale) throws ParseException;
}

public interface Formatter<T> extends Printer<T>, Parser<T> {
}

Formatter接口中拥有两个方法,一个是解析字符串的parse,一个是将字符串格式化的print,两个方法都拥有Locale类型的参数,因此还可根据地区来做出相应的定制。

那么如何使用Formatter呢?由于注解的出现,大量需要在xml中的配置项都直接换为注解的方式,Formatter也是,Spring提供了AnnotationFormatterFactory这个接口。

AnnotationFormatterFactory<A extends Annotation>

public interface AnnotationFormatterFactory<A extends Annotation> {

    Set<Class<?>> getFieldTypes();

    Printer<?> getPrinter(A annotation, Class<?> fieldType);

    Parser<?> getParser(A annotation, Class<?> fieldType);
    
}

getFieldTypes方法返回的是当这些类型有A注解的时候我才会做格式化操作,getPrinter方法和getParser则分别获取相应的对象,我们也可以直接将Formatter对象返回。

如何使用

格式化的操作,本质上来说也是类型转换,即String => ? 和? => String。因此Spring将转换器与格式化同质化,在代码实现中,Formatter也是被转换为相应的Printer转换器和Parser转换器,那么,Formatter也就可以注册到ConversionService中了。

可以注册Formatter的接口为FormatterRegistry,该接口继承自ConverterRegistry,将它与ConversionService一起实现的类是FormattingConversionService

public interface FormatterRegistry extends ConverterRegistry {

    void addFormatter(Formatter<?> formatter);

    void addFormatterForFieldType(Class<?> fieldType, Formatter<?> formatter);

    void addFormatterForFieldType(Class<?> fieldType, Printer<?> printer, Parser<?> parser);

    void addFormatterForFieldAnnotation(AnnotationFormatterFactory<? extends Annotation> annotationFormatterFactory);

}

令人非常遗憾的是,除了通过ConversionServiceconvert直接使用,Formatterprint方法通过框架使用的条件比较特殊,它需要spring标签的支持才能做到在页面上的格式化,parse只需要在相应字段上打上注解即可。

写写代码

说了这么多,自然还是来点代码更实在。

对于ConverterConverterFactory以及Formatter,使用在SpringMVC的参数绑定上的机会会更多,所以直接在web项目里写。而ConditionalGenericConverter接口官方实现的例子已经很丰富了,至少我没想到什么新的需求,想要看代码的话可以直接去看官方的源码(比如ArrayToCollectionConverter),我就不自己写了。

以下代码基于SpringBoot 2.1.1,对应的SpringMVC为5.1.3,使用了lombok

@RestController
@RequestMapping("test")
public class TestController {
    @GetMapping("/index")
    public UserEntity test(UserEntity user) {
        return user;
    }
}
@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addFormatters(FormatterRegistry registry) {
        // 为webMVC注册转换器
        registry.addConverter(new String2StatusEnumConverter());
        registry.addConverterFactory(new String2EnumConverterFactory());
        registry.addFormatterForFieldAnnotation(new GenderFormatterFactory());
    }
}
@Data
@Component
public class UserEntity {

    private String username;
    private String password;

    // 加上注解的含义为使用枚举的name字段进行枚举的格式化,可改为id
    @GenderEnumFormat("name")
    private GenderEnum gender;

    private StatusEnum status;

}
public interface EnumInterface {
    Integer getId();
}
@Getter
@AllArgsConstructor
public enum GenderEnum implements EnumInterface {

    MALE(0, "男"),
    FEMALE(1, "女"),
    ;

    private Integer id;
    private String name;
}
@Getter
@AllArgsConstructor
public enum StatusEnum implements EnumInterface {
    ON(1, "启用"),
    OFF(0, "停用"),
    ;

    private Integer id;
    private String name;

}
/**
 * String to StatusEnum 的转换器
 */
public class String2StatusEnumConverter implements Converter<String, StatusEnum> {

    @Override
    public StatusEnum convert(String s) {
        // 注意,这里是通过id匹配
        for (StatusEnum e : StatusEnum.values()) {
            if (e.getId().equals(Integer.valueOf(s))) {
                return e;
            }
        }
        return null;
    }
}
/**
 * String to EnumInterface 的转换器工厂
 */
public class String2EnumConverterFactory implements ConverterFactory<String, EnumInterface> {

    @Override
    public <T extends EnumInterface> Converter<String, T> getConverter(Class<T> targetType) {
        return new String2Enum<>(targetType);
    }

    /**
     * 转换器
     */
    private class String2Enum<T extends EnumInterface> implements Converter<String, T> {

        private final Class<T> targetType;

        private String2Enum(Class<T> targetType) {
            this.targetType = targetType;
        }

        @Override
        public T convert(String source) {
            for (T enumConstant : targetType.getEnumConstants()) {
                if (enumConstant.getId().toString().equals(source)) {
                    return enumConstant;
                }
            }
            return null;
        }
    }
}
/**
 * 将打上注解的GenderEnum通过特定的字段转换为枚举
 */
@Target({ElementType.TYPE, ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
public @interface GenderEnumFormat {
    String value();
}
public class GenderFormatterFactory implements AnnotationFormatterFactory<GenderEnumFormat> {
    @Override
    public Set<Class<?>> getFieldTypes() {
        return Collections.singleton(GenderEnum.class);
    }

    @Override
    public Printer<?> getPrinter(GenderEnumFormat annotation, Class<?> fieldType) {
        return new GenderFormatter(annotation.value());
    }

    @Override
    public Parser<?> getParser(GenderEnumFormat annotation, Class<?> fieldType) {
        return new GenderFormatter(annotation.value());
    }

    final class GenderFormatter implements Formatter<GenderEnum> {
        private final String fieldName;
        private Method getter;

        private GenderFormatter(String fieldName) {
            this.fieldName = fieldName;
        }

        @Override
        public GenderEnum parse(String text, Locale locale) throws ParseException {
            if (getter == null) {
                try {
                    getter = GenderEnum.class.getMethod("get" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1));
                } catch (NoSuchMethodException e) {
                    throw new ParseException(e.getMessage(), 0);
                }
            }
            for (GenderEnum e : GenderEnum.values()) {
                try {
                    if (getter.invoke(e).equals(text)) {
                        return e;
                    }
                } catch (IllegalAccessException | InvocationTargetException e1) {
                    throw new ParseException(e1.getMessage(), 0);
                }
            }
            throw new ParseException("输入参数有误,不存在这样的枚举值:" + text, 0);
        }

        @Override
        public String print(GenderEnum object, Locale locale) {
            try {
                // 这里应该也判断一下getter是否为null然后选择进行初始化,但是因为print方法没有效果所以也懒得写了
                return getter.invoke(object).toString();
            } catch (IllegalAccessException | InvocationTargetException e) {
                return e.getMessage();
            }
        }
    }
}

源码笔记

之前一直说类型转换在Spring MVC的参数绑定中有用到,下面就放一下本人的一些笔记。由于实力问题有些地方也有些懵逼,也欢迎大家交流。

(看源码的时候突然遇到IDEA无法下载源码,搜出来的结果大致都是说更换maven版本,懒得更改就直接用maven命令下载源码了:

mvn dependency:sources -DincludeArtifactIds=spring-webmvc

不加参数的话会默认下载全部的源码)

public class InvocableHandlerMethod extends HandlerMethod {
        // ...
        protected Object[] getMethodArgumentValues(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer, Object... providedArgs) throws Exception {
            if (ObjectUtils.isEmpty(this.getMethodParameters())) {
                return EMPTY_ARGS;
            } else {
                // 得到处理方法的方法参数
                MethodParameter[] parameters = this.getMethodParameters();
                Object[] args = new Object[parameters.length];

                for (int i = 0; i < parameters.length; ++i) {
                    MethodParameter parameter = parameters[i];
                    // 初始化,之后可以调用MethodParameter对象的getParameterName方法
                    parameter.initParameterNameDiscovery(this.parameterNameDiscoverer);
                    // 如果providedArgs包含当前参数的类型就赋值
                    args[i] = findProvidedArgument(parameter, providedArgs);
                    if (args[i] == null) {
                        // resolvers包含了所有的参数解析器(HandlerMethodArgumentResolver的实现类,常见的比如RequestParamMethodArgumentResolver,PathVariableMethodArgumentResolver等,就是在参数前加的注解的处理类,有对应的注解的话就会用对应的解析器去处理参数绑定,如果没有注解的话通常会和有ModelAttribute注解一样使用ServletModelAttributeMethodProcessor,具体判断在每个实现类的supportsParameter方法里)
                        if (!this.resolvers.supportsParameter(parameter)) {
                            throw new IllegalStateException(formatArgumentError(parameter, "No suitable resolver"));
                        }

                        try {
                            // 使用解析器开始解析参数
                            args[i] = this.resolvers.resolveArgument(parameter, mavContainer, request, this.dataBinderFactory);
                        } catch (Exception var10) {
                            if (this.logger.isDebugEnabled()) {
                                String error = var10.getMessage();
                                if (error != null && !error.contains(parameter.getExecutable().toGenericString())) {
                                    this.logger.debug(formatArgumentError(parameter, error));
                                }
                            }

                            throw var10;
                        }
                    }
                }

                return args;
            }
        }
        // ...
    }

public abstract class AbstractNamedValueMethodArgumentResolver implements HandlerMethodArgumentResolver {
    // ...
    public final Object resolveArgument(MethodParameter parameter, @Nullable ModelAndViewContainer mavContainer,
                                        NativeWebRequest webRequest, @Nullable WebDataBinderFactory binderFactory) throws Exception {
        // 获取paramter的信息,NamedValueInfo包含参数的名称、是否必填、默认值,其实就是该参数在RequestParam注解中的配置
        NamedValueInfo namedValueInfo = getNamedValueInfo(parameter);
        // 如果parameter是Optional类型,那么就产生一个指向相同参数对象但嵌套等级(nestingLevel)+1的MethodParameter
        MethodParameter nestedParameter = parameter.nestedIfOptional();
        // 先后解析配置项与SPEL表达式(即${}、#{})
        Object resolvedName = resolveStringValue(namedValueInfo.name);
        if (resolvedName == null) {
            throw new IllegalArgumentException(
                    "Specified name must not resolve to null: [" + namedValueInfo.name + "]");
        }
        // 从请求(request)中获取对应名称的数据,如果非上传文件,就相当于servlet中的request.getParameter(),另外如果有多个符合name的值会返回String[]
        Object arg = resolveName(resolvedName.toString(), nestedParameter, webRequest);
        if (arg == null) {
            if (namedValueInfo.defaultValue != null) {
                // 请求中没有这个参数并且有默认值就将解析defaultValue后值的设为参数
                arg = resolveStringValue(namedValueInfo.defaultValue);
            } else if (namedValueInfo.required && !nestedParameter.isOptional()) {
                // 参数必填且方法的类型要求不是Optional的话抛异常
                handleMissingValue(namedValueInfo.name, nestedParameter, webRequest);
            }
            // 处理null值。如果参数类型(或者被Optional包裹的类型)是Boolean会转换成false,而如果参数类型是基本类型的话会抛出异常(因为基本类型值不能为null)
            arg = handleNullValue(namedValueInfo.name, arg, nestedParameter.getNestedParameterType());
        } else if ("".equals(arg) && namedValueInfo.defaultValue != null) {
            // 如果有默认值将会把空字符串处理为默认值
            arg = resolveStringValue(namedValueInfo.defaultValue);
        }

        if (binderFactory != null) {
            // biner中有conversionService的实例,而conversionService中就包含着全部可用的转换器。
            WebDataBinder binder = binderFactory.createBinder(webRequest, null, namedValueInfo.name);
            try {
                // 开始真正的类型转换
                arg = binder.convertIfNecessary(arg, parameter.getParameterType(), parameter);
            } catch (ConversionNotSupportedException ex) {
                throw new MethodArgumentConversionNotSupportedException(arg, ex.getRequiredType(),
                        namedValueInfo.name, parameter, ex.getCause());
            } catch (TypeMismatchException ex) {
                throw new MethodArgumentTypeMismatchException(arg, ex.getRequiredType(),
                        namedValueInfo.name, parameter, ex.getCause());

            }
        }

        // 钩子方法,重写这个方法的暂时只有PathVariableMethodArgumentResolver
        handleResolvedValue(arg, namedValueInfo.name, parameter, mavContainer, webRequest);

        return arg;
    }
    // ...
}
class TypeConverterDelegate {
    // ...

    /**
     * Convert the value to the required type (if necessary from a String),
     * for the specified property.
     *
     * @param propertyName   name of the property
     * @param oldValue       the previous value, if available (may be {@code null})
     * @param newValue       the proposed new value
     * @param requiredType   the type we must convert to
     *                       (or {@code null} if not known, for example in case of a collection element)
     * @param typeDescriptor the descriptor for the target property or field
     * @return the new value, possibly the result of type conversion
     * @throws IllegalArgumentException if type conversion failed
     */
    @SuppressWarnings("unchecked")
    @Nullable
    public <T> T convertIfNecessary(@Nullable String propertyName, @Nullable Object oldValue, @Nullable Object newValue,
                                    @Nullable Class<T> requiredType, @Nullable TypeDescriptor typeDescriptor) throws IllegalArgumentException {
        // 在当前的流程中propertyName、oldValue为null,newValue为前台传过来的真实参数值,requiredType为处理方法要求的类型,typeDescriptor为要求类型的描述封装类

        // Custom editor for this type?
        PropertyEditor editor = this.propertyEditorRegistry.findCustomEditor(requiredType, propertyName);

        ConversionFailedException conversionAttemptEx = null;

        // No custom editor but custom ConversionService specified?
        ConversionService conversionService = this.propertyEditorRegistry.getConversionService();
        if (editor == null && conversionService != null && newValue != null && typeDescriptor != null) {
            // 上述条件成立
            // 在现在的逻辑里sourceTypeDesc必然为String的TypeDescriptor
            TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
            if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
                // 可以转换
                // canConvert实际上是尝试获取符合条件的GenericConverter,如果有就说明可以转换
                // 对于String -> Integer的转换,会先将String类型拆为 [String,Serializable,Comparable,CharSequence,Object]的类型层,Integer同样拆为自己的类型层,之后先后遍历每个类型来准确判断是否存在可以转换的转换器
                try {
                    // 最终会调用到自定义的转换器
                    return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
                } catch (ConversionFailedException ex) {
                    // fallback to default conversion logic below
                    // 转换失败,暂存异常,将会执行默认的转换逻辑
                    conversionAttemptEx = ex;
                }
            }
        }
        // 因为spring自带了很多常见类型的转换器,大部分都可以通过上面的转换器完成。
        // 程序运行到这里没有结束的话很可能说明类型是没有定义转换器的自定义类型或者参数格式真的不正确

        Object convertedValue = newValue;

        // Value not of required type?
        if (editor != null || (requiredType != null && !ClassUtils.isAssignableValue(requiredType, convertedValue))) {
            // 最后的条件为 当newValue不是requiredType的实例
            if (typeDescriptor != null && requiredType != null && Collection.class.isAssignableFrom(requiredType) &&
                    convertedValue instanceof String) {
                // isAssignableFrom用来判断Collection是否为requiredType的父类或者接口,或者二者是否为同一类型或接口
                TypeDescriptor elementTypeDesc = typeDescriptor.getElementTypeDescriptor();
                if (elementTypeDesc != null) {
                    Class<?> elementType = elementTypeDesc.getType();
                    if (Class.class == elementType || Enum.class.isAssignableFrom(elementType)) {
                        // 相当于convertedValue.split(",")
                        convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                    }
                }
            }
            if (editor == null) {
                editor = findDefaultEditor(requiredType);
            }
            // 使用默认的editor进行转换,不过默认的editor的转换有可能与期望的不一致。(比如 "1,2,3,4" -> ArrayList<String>{"1,2,3,4"},结果是只有一个元素的list)
            convertedValue = doConvertValue(oldValue, convertedValue, requiredType, editor);
        }

        boolean standardConversion = false;

        // 加下来会根据requiredType来做出相应的转换
        if (requiredType != null) {
            // Try to apply some standard type conversion rules if appropriate.

            if (convertedValue != null) {
                if (Object.class == requiredType) {
                    // requiredType是Object
                    return (T) convertedValue;
                } else if (requiredType.isArray()) {
                    // requiredType是数组
                    // Array required -> apply appropriate conversion of elements.
                    if (convertedValue instanceof String && Enum.class.isAssignableFrom(requiredType.getComponentType())) {
                        convertedValue = StringUtils.commaDelimitedListToStringArray((String) convertedValue);
                    }
                    return (T) convertToTypedArray(convertedValue, propertyName, requiredType.getComponentType());
                } else if (convertedValue instanceof Collection) {
                    // 将convertedValue转换为集合,内部对每个元素调用了convertIfNecessary(即本方法)
                    // Convert elements to target type, if determined.
                    convertedValue = convertToTypedCollection(
                            (Collection<?>) convertedValue, propertyName, requiredType, typeDescriptor);
                    standardConversion = true;
                } else if (convertedValue instanceof Map) {
                    // 将convertedValue转换为Map
                    // Convert keys and values to respective target type, if determined.
                    convertedValue = convertToTypedMap(
                            (Map<?, ?>) convertedValue, propertyName, requiredType, typeDescriptor);
                    standardConversion = true;
                }
                if (convertedValue.getClass().isArray() && Array.getLength(convertedValue) == 1) {
                    convertedValue = Array.get(convertedValue, 0);
                    standardConversion = true;
                }
                if (String.class == requiredType && ClassUtils.isPrimitiveOrWrapper(convertedValue.getClass())) {
                    // We can stringify any primitive value...
                    return (T) convertedValue.toString();
                } else if (convertedValue instanceof String && !requiredType.isInstance(convertedValue)) {
                    if (conversionAttemptEx == null && !requiredType.isInterface() && !requiredType.isEnum()) {
                        try {
                            Constructor<T> strCtor = requiredType.getConstructor(String.class);
                            return BeanUtils.instantiateClass(strCtor, convertedValue);
                        } catch (NoSuchMethodException ex) {
                            // proceed with field lookup
                            if (logger.isTraceEnabled()) {
                                logger.trace("No String constructor found on type [" + requiredType.getName() + "]", ex);
                            }
                        } catch (Exception ex) {
                            if (logger.isDebugEnabled()) {
                                logger.debug("Construction via String failed for type [" + requiredType.getName() + "]", ex);
                            }
                        }
                    }
                    String trimmedValue = ((String) convertedValue).trim();
                    if (requiredType.isEnum() && trimmedValue.isEmpty()) {
                        // It's an empty enum identifier: reset the enum value to null.
                        return null;
                    }
                    // 尝试转换为枚举
                    convertedValue = attemptToConvertStringToEnum(requiredType, trimmedValue, convertedValue);
                    standardConversion = true;
                } else if (convertedValue instanceof Number && Number.class.isAssignableFrom(requiredType)) {
                    convertedValue = NumberUtils.convertNumberToTargetClass(
                            (Number) convertedValue, (Class<Number>) requiredType);
                    standardConversion = true;
                }
            } else {
                // convertedValue == null
                if (requiredType == Optional.class) {
                    convertedValue = Optional.empty();
                }
            }

            if (!ClassUtils.isAssignableValue(requiredType, convertedValue)) {
                if (conversionAttemptEx != null) {
                    // Original exception from former ConversionService call above...
                    throw conversionAttemptEx;
                } else if (conversionService != null && typeDescriptor != null) {
                    // ConversionService not tried before, probably custom editor found
                    // but editor couldn't produce the required type...
                    TypeDescriptor sourceTypeDesc = TypeDescriptor.forObject(newValue);
                    if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
                        return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
                    }
                }

                // Definitely doesn't match: throw IllegalArgumentException/IllegalStateException
                StringBuilder msg = new StringBuilder();
                msg.append("Cannot convert value of type '").append(ClassUtils.getDescriptiveType(newValue));
                msg.append("' to required type '").append(ClassUtils.getQualifiedName(requiredType)).append("'");
                if (propertyName != null) {
                    msg.append(" for property '").append(propertyName).append("'");
                }
                if (editor != null) {
                    msg.append(": PropertyEditor [").append(editor.getClass().getName()).append(
                            "] returned inappropriate value of type '").append(
                            ClassUtils.getDescriptiveType(convertedValue)).append("'");
                    throw new IllegalArgumentException(msg.toString());
                } else {
                    msg.append(": no matching editors or conversion strategy found");
                    throw new IllegalStateException(msg.toString());
                }
            }
        }

        if (conversionAttemptEx != null) {
            if (editor == null && !standardConversion && requiredType != null && Object.class != requiredType) {
                throw conversionAttemptEx;
            }
            logger.debug("Original ConversionService attempt failed - ignored since " +
                    "PropertyEditor based conversion eventually succeeded", conversionAttemptEx);
        }

        return (T) convertedValue;
    }
    // ...
}

最后

看源码虽然很费时间,但是的确是能学到很多东西的,而且也能发现很多以前不知道的事情(比如RequestParam注解的name和defaultName参数是可以嵌套引用配置文件中的内容,也可以写SPEL表达式),但其中还是有一些地方不是很清楚。

虽说现在项目都直接使用JSON做前后端交互,大部分类型转换的任务都交给了JSON序列化框架,但是参数绑定这里还是值得看一看,等到需要用的时候就可以直接拿出来用。

猜你喜欢

转载自www.cnblogs.com/baka-sky/p/10200845.html