好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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

找入口

请求入口是dispatcherservlet

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

ha.handle(processedrequest, response, mappedhandler.gethandler())逻辑。

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

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

org.springframework.web.method.support.invocablehandlermethod#invokeforrequest的逻辑:

?

1

2

3

4

5

6

7

8

9

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方法

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

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

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

获取输入参数的逻辑在

org.springframework.web.method.annotation.requestparammethodargumentresolver#resolvename

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

核心代码如下:

?

1

2

3

4

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方法中

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

?

1

2

3

4

5

6

7

8

9

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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 ;

}

转换为伪代码就是:

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

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

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

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

spring 如何查找转换器

org.springframework.core.convert.support.genericconversionservice.converters#find

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

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方法

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

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

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

方法,代码如下:

?

1

2

3

4

5

6

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对应转换器的枚举参数的资料请关注其它相关文章!

原文链接:https://blog.csdn.net/liuxinghao/article/details/119725983

查看更多关于SpringBoot实战:Spring如何找到对应转换器优雅使用枚举参数的详细内容...

  阅读:16次