广告
返回顶部
首页 > 资讯 > 后端开发 > Python >SpringBoot实战:Spring如何找到对应转换器优雅使用枚举参数
  • 261
分享到

SpringBoot实战:Spring如何找到对应转换器优雅使用枚举参数

2024-04-02 19:04:59 261人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

目录找入口请求入口是DispatcherServlet查找转换器spring 如何查找转换器类型转换跟随源码找到自定义转换器工厂类和转换器类的实现逻辑无论是GET请求,还是传参式的P

找入口

请求入口是DispatcherServlet

所有的请求最终都会落到doDispatch方法中的

ha.handle(processedRequest, response, mappedHandler.getHandler())逻辑。

我们从这里出发,一层一层向里扒。

跟着代码深入,我们会找到

org.springframework.WEB.method.support.InvocableHandlerMethod#invokeForRequest的逻辑:


public Object invokeForRequest(NativeWebRequest request, @Nullable ModelAndViewContainer mavContainer,
        Object... providedArgs) throws Exception {

    Object[] args = getMethodArgumentValues(request, mavContainer, providedArgs);
    if (logger.isTraceEnabled()) {
        logger.trace("Arguments: " + Arrays.toString(args));
    }
    return doInvoke(args);
}

可以看出,这里面通过getMethodArgumentValues方法处理参数,然后调用doInvoke方法获取返回值。

继续深入,能够找到

org.springframework.web.method.annotation.RequestParamMethodArgumentResolver#resolveArgument方法

这个方法就是解析参数的逻辑。

试想一下,如果是我们自己实现这段逻辑,会怎么做呢?

  1. 输入参数
  2. 找到目标参数
  3. 检查是否需要特殊转换逻辑
  4. 如果需要,进行转换
  5. 如果不需要,直接返回

解析参数

获取输入参数的逻辑在

org.springframework.web.method.annotation.RequestParamMethodArgumentResolver#resolveName

单参数返回的是 String 类型,多参数返回 String 数组

核心代码如下:


String[] paramValues = request.getParameterValues(name);
if (paramValues != null) {
    arg = (paramValues.length == 1 ? paramValues[0] : paramValues);
}

所以说,无论我们的目标参数是什么,输入参数都是 String 类型或 String 数组

  • 然后 Spring 把它们转换为我们期望的类型。
  • 找到目标参数的逻辑在DispatcherServlet中,根据 uri 找到对应的 Controller 处理方法
  • 找到方法就找到了目标参数类型。
  • 接下来就是检查是否需要转换逻辑,也就是
  • org.springframework.validation.DataBinder#convertIfNecessary
  • 顾名思义,如果需要就转换,将字符串类型转换为目标类型。

在我们的例子中,就是将 String 转换为枚举值。

查找转换器

org.springframework.beans.TypeConverterDelegate#convertIfNecessary方法中

继续深扒找到这么一段逻辑:


if (conversionService.canConvert(sourceTypeDesc, typeDescriptor)) {
    try {
        return (T) conversionService.convert(newValue, sourceTypeDesc, typeDescriptor);
    }
    catch (ConversionFailedException ex) {
        // fallback to default conversion logic below
        conversionAttemptEx = ex;
    }
}

这段逻辑中,调用了

 org.springframework.core.convert.support.GenericConversionService#canConvert方法

检查是否可转换,如果可以转换,将会执行类型转换逻辑。

检查是否可转换的本质就是检查是否能够找到对应的转换器。

  • 如果能找到,就用找到的转换器开始转换逻辑
  • 如果找不到,那就是不能转换,走其他逻辑。

我们可以看看查找转换器的代码

org.springframework.core.convert.support.GenericConversionService#getConverter

可以对我们自己写代码有一些启发:


private final Map<ConverterCacheKey, GenericConverter> converterCache = new ConcurrentReferenceHashMap<>(64);
protected GenericConverter getConverter(TypeDescriptor sourceType, TypeDescriptor targetType) {
    ConverterCacheKey key = new ConverterCacheKey(sourceType, targetType);
    GenericConverter converter = this.converterCache.get(key);
    if (converter != null) {
        return (converter != NO_MATCH ? converter : null);
    }
    converter = this.converters.find(sourceType, targetType);
    if (converter == null) {
        converter = getDefaultConverter(sourceType, targetType);
    }
    if (converter != null) {
        this.converterCache.put(key, converter);
        return converter;
    }
    this.converterCache.put(key, NO_MATCH);
    return null;
}

转换为伪代码就是:

  1. 根据参数类型和目标类型,构造缓存 key
  2. 根据缓存 key从缓存中查询转换器
  3. 如果能找到且不是 NO_MATCH,返回转换器;如果是 NO_MATCH,返回 null;如果未找到,继续
  4. 通过org.springframework.core.convert.support.GenericConversionService.Converters#find查询转换器
  5. 如果未找到,检查源类型和目标类型是否可以强转,也就是类型一致。如果是,返回 NoOpConverter,如果否,返回 null。
  6. 检查找到的转换器是否为 null,如果不是,将转换器加入到缓存中,返回该转换器
  7. 如果否,在缓存中添加 NO_MATCH 标识,返回 null

查找转换器

Spring 内部使用Map作为缓存,用来存储通用转换器接口GenericConverter,这个接口会是我们自定义转换器的包装类。

  • 我们还可以看到,转换器缓存用的是ConcurrentReferenceHashMap,这个类是线程安全
  • 可以保证并发情况下,不会出现异常存储。但是getConverter方法没有使用同步逻辑。
  • 换句话说,并发请求时,可能存在性能损耗。

不过,对于 web 请求场景,并发损耗好过阻塞等待。

Spring 如何查找转换器

org.springframework.core.convert.support.GenericConversionService.Converters#find

就是找到对应转换器的核心逻辑:


private final Map<ConvertiblePair, ConvertersForPair> converters = new ConcurrentHashMap<>(256);
@Nullable
public GenericConverter find(TypeDescriptor sourceType, TypeDescriptor targetType) {
    // Search the full type hierarchy
    List<Class<?>> sourceCandidates = getClasshierarchy(sourceType.getType());
    List<Class<?>> targetCandidates = getClassHierarchy(targetType.getType());
    for (Class<?> sourceCandidate : sourceCandidates) {
        for (Class<?> targetCandidate : targetCandidates) {
            ConvertiblePair convertiblePair = new ConvertiblePair(sourceCandidate, targetCandidate);
            GenericConverter converter = getReGISteredConverter(sourceType, targetType, convertiblePair);
            if (converter != null) {
                return converter;
            }
        }
    }
    return null;
}

@Nullable
private GenericConverter getRegisteredConverter(TypeDescriptor sourceType,
        TypeDescriptor targetType, ConvertiblePair convertiblePair) {
    // Check specifically registered converters
    ConvertersForPair convertersForPair = this.converters.get(convertiblePair);
    if (convertersForPair != null) {
        GenericConverter converter = convertersForPair.getConverter(sourceType, targetType);
        if (converter != null) {
            return converter;
        }
    }
    // Check ConditionalConverters for a dynamic match
    for (GenericConverter globalConverter : this.globalConverters) {
        if (((ConditionalConverter) globalConverter).matches(sourceType, targetType)) {
            return globalConverter;
        }
    }
    return null;
}

我们可以看到,Spring 是通过源类型和目标类型组合起来,查找对应的转换器。

而且,Spring 还通过getClassHierarchy方法,将源类型和目标类型的家族族谱全部列出来,用双层 for 循环遍历查找。

上面的代码中,还有一个matches方法,在这个方法里面,调用了ConverterFactory#getConverter方法

也就是用这个工厂方法,创建了指定类型的转换器。


private final ConverterFactory<Object, Object> converterFactory;
public boolean matches(TypeDescriptor sourceType, TypeDescriptor targetType) {
    boolean matches = true;
    if (this.converterFactory instanceof ConditionalConverter) {
        matches = ((ConditionalConverter) this.converterFactory).matches(sourceType, targetType);
    }
    if (matches) {
        Converter<?, ?> converter = this.converterFactory.getConverter(targetType.getType());
        if (converter instanceof ConditionalConverter) {
            matches = ((ConditionalConverter) converter).matches(sourceType, targetType);
        }
    }
    return matches;
}

类型转换

经过上面的逻辑,已经找到判断可以进行转换。

org.springframework.core.convert.support.GenericConversionService#convert

其核心逻辑就是已经找到对应的转换器了,下面就是转换逻辑


public Object convert(@Nullable Object source, @Nullable TypeDescriptor sourceType, TypeDescriptor targetType) {
    Assert.notNull(targetType, "Target type to convert to cannot be null");
    if (sourceType == null) {
        Assert.isTrue(source == null, "Source must be [null] if source type == [null]");
        return handleResult(null, targetType, convertNullSource(null, targetType));
    }
    if (source != null && !sourceType.getObjectType().isInstance(source)) {
        throw new IllegalArgumentException("Source to convert from must be an instance of [" +
                sourceType + "]; instead it was a [" + source.getClass().getName() + "]");
    }
    GenericConverter converter = getConverter(sourceType, targetType);
    if (converter != null) {
        Object result = ConversionUtils.invokeConverter(converter, source, sourceType, targetType);
        return handleResult(sourceType, targetType, result);
    }
    return handleConverterNotFound(source, sourceType, targetType);
}

其中的GenericConverter converter = getConverter(sourceType, targetType)就是前文中getConverter方法。

  • 此处还是可以给我们编码上的一些借鉴的:getConverter方法在canConvert中调用了一次
    然后在后续真正转换的时候又调用一次这是参数转换逻辑
  • 我们该怎么优化这种同一请求内多次调用相同逻辑或者请求相同参数呢?
    那就是使用缓存。为了保持一次请求中前后两次数据的一致性和请求的高效,推荐使用内存缓存。

执行到这里,直接调用

ConversionUtils.invokeConverter(converter, source, sourceType, targetType)转换

其内部是使用

org.springframework.core.convert.support.GenericConversionService.ConverterFactoryAdapter#convert

方法,代码如下:


public Object convert(@Nullable Object source, TypeDescriptor sourceType, TypeDescriptor targetType) {
    if (source == null) {
        return convertNullSource(sourceType, targetType);
    }
    return this.converterFactory.getConverter(targetType.getObjectType()).convert(source);
}

这里就是调用ConverterFactory工厂类构建转换器(即IdCodeToEnumConverterFactory类的getConverter方法)

然后调用转换器的conver方法(即IdCodeToEnumConverter类的convert方法),将输入参数转换为目标类型。

具体实现可以看一下实战篇中的代码,这里不做赘述。

至此,我们把整个路程通了下来。

跟随源码找到自定义转换器工厂类和转换器类的实现逻辑

无论是GET请求,还是传参式的POST请求(即Form模式)

这里需要强调一下的是,由于实战篇中我们用到的例子是简单参数的方式,也就是Controller的方法参数都是直接参数

  • 没有包装成对象。这样的话,Spring 是通过RequestParamMethodArgumentResolver处理参数。
  • 如果是包装成对象,会使用ModelAttributeMethodProcessor处理参数。这两个处理类中查找类型转换器逻辑都是相同的。
  • 都可以使用上面这种方式,实现枚举参数的类型转换。

但是 Http Body 方式却不行,为什么呢?

  • Spring 对于 body 参数是通过RequestResponseBodyMethodProcessor处理的
  • 其内部使用了MappingJackson2HttpMessageConverter转换器,逻辑完全不同。

所以,想要实现 body 的类型转换,还需要走另外一种方式,更多关于Spring对应转换器的枚举参数的资料请关注编程网其它相关文章!

--结束END--

本文标题: SpringBoot实战:Spring如何找到对应转换器优雅使用枚举参数

本文链接: https://www.lsjlt.com/news/133206.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作