DoneSpeak

SpringMVC在Controller层方法的参数解析

字数: 1.1k时长: 5 min
2021/12/25 Share

写在前面

使用版本:

1
2
3
spring-boot: 2.1.6.RELEASE
sping: 5.1.8.RELEASE
java: openjdk 11.0.13

自定义参数解析器

为了能够实现自定义参数解析器,只需要实现HandlerMethodArgumentResolver并将添加到WebMvcConfigurer#addArgumentResolvers即可。

实现效果

下面以添加一个获取请求头的client-type参数为例进行是实现。定义注解@ClientTypeMark以及enumClientType,用于注入header中的值。

1
2
3
4
5
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ClientTypeMark {
}
1
2
3
4
5
6
public enum ClientType {
WEB,
MOBILE,
UNKNOWN
;
}

最终实现的效果为在Controller的方法中,可以按照如下实现使用。

1
2
3
4
5
6
7
8
9
@RestController
@RequestMapping("/client")
public class ClientTypeEndpoint {

@GetMapping("/cur")
public ClientType getCurClientType(@ClientTypeMark ClientType clientType) {
return clientType;
}
}

实现和配置

按照如下方法实现HandlerMethodArgumentResolver,用于解析header中的client-type并转化为ClientType

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
38
package io.github.donespeak.springbootsamples.web.common;

import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class CurClientTypeMethodArgumentResolver implements HandlerMethodArgumentResolver {

private final String[] CLIENT_TYPE_HEADER_NAMES = {"client-type", "CLIENT-TYPE", "Client-Type"};

// 选择要被注入的参数:判断参数是否符合解析的条件
@Override
public boolean supportsParameter(MethodParameter param) {
return param.hasParameterAnnotation(ClientTypeMark.class)
&& ClientType.class.isAssignableFrom(param.getParameterType());
}

// 返回值将被注入到被选中参数中
@Override
public Object resolveArgument(MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer,
NativeWebRequest nativeWebRequest, WebDataBinderFactory webDataBinderFactory) throws Exception {
String clientType = null;
for (String clientTypeHeader: CLIENT_TYPE_HEADER_NAMES) {
clientType = nativeWebRequest.getHeader(clientTypeHeader);
if (StringUtils.isNotBlank(clientType)) {
break;
}
}
try {
return StringUtils.isBlank(clientType) ? ClientType.UNKNOWN : ClientType.valueOf(clientType.toUpperCase());
} catch (Exception e) {
return ClientType.UNKNOWN;
}
}
}

为了使得配置能够生效,可以按照如下的方法添加解析器。

1
2
3
4
5
6
7
8
9
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
// 解析@CurUserId注解的参数
argumentResolvers.add(new CurClientTypeMethodArgumentResolver());
}
}

至此,自定义参数解析器的工作就完成了。

Spring提供解析器

当你完成上面的自定义解析器的时候,大体就能知道Spring在Controller层的其他参数解析都是怎么实现的了。

如下是Spring Mvc默认的一些参数解析器。

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
package org.springframework.web.servlet.mvc.method.annotation;

public class RequestMappingHandlerAdapter extends AbstractHandlerMethodAdapter
implements BeanFactoryAware, InitializingBean {
...
/**
* Return the list of argument resolvers to use including built-in resolvers
* and custom resolvers provided via {@link #setCustomArgumentResolvers}.
*/
private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers() {
List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>();

// Annotation-based argument resolution
// 解析:@RequestParam(required = false)
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false));
// 解析:@RequestParam Map
resolvers.add(new RequestParamMapMethodArgumentResolver());
// 解析:@PathVariable
resolvers.add(new PathVariableMethodArgumentResolver());
// 解析:@PathVariable Map
resolvers.add(new PathVariableMapMethodArgumentResolver());
// 解析:@MatrixVariable
resolvers.add(new MatrixVariableMethodArgumentResolver());
// 解析:@MatrixVariable Map
resolvers.add(new MatrixVariableMapMethodArgumentResolver());
// 解析:@ModelAttribute(required = false)
resolvers.add(new ServletModelAttributeMethodProcessor(false));
// 解析:@RequestBody
resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
// 解析:@RequestPart
resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this.requestResponseBodyAdvice));
// 解析:@RequestHeader
resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory()));
// 解析:@RequestHeader Map
resolvers.add(new RequestHeaderMapMethodArgumentResolver());
// 解析:@CookieValue
resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory()));
// 解析:@Value
resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory()));
// 解析:@SessionAttribute
resolvers.add(new SessionAttributeMethodArgumentResolver());
// 解析:@RequestAttribute
resolvers.add(new RequestAttributeMethodArgumentResolver());

// Type-based argument resolution
// 解析:WebRequest、ServletRequest、MultipartRequest、HttpSession、
// Principal、Locale、TimeZone、java.time.ZoneId、InputStream
// java.io.Reader、org.springframework.http.HttpMethod
resolvers.add(new ServletRequestMethodArgumentResolver());
// 解析:ServletResponse、OutputStream、Writer
resolvers.add(new ServletResponseMethodArgumentResolver());
// 解析:@HttpEntity、@RequestEntity
resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this.requestResponseBodyAdvice));
// 解析:RedirectAttributes
resolvers.add(new RedirectAttributesMethodArgumentResolver());
// 解析:org.springframework.ui.Model, 值为ModelAndViewContainer#getModel
resolvers.add(new ModelMethodProcessor());
// 解析:Map, 值为ModelAndViewContainer#getModel
resolvers.add(new MapMethodProcessor());
// 解析:org.springframework.validation.Errors
resolvers.add(new ErrorsMethodArgumentResolver());
// 解析:org.springframework.web.bind.support.SessionStatus
resolvers.add(new SessionStatusMethodArgumentResolver());
// 解析:UriComponentsBuilder 或者 ServletUriComponentsBuilder
resolvers.add(new UriComponentsBuilderMethodArgumentResolver());

// Custom arguments
if (getCustomArgumentResolvers() != null) {
resolvers.addAll(getCustomArgumentResolvers());
}

// Catch-all
// 解析:@RequestParam(required = true)
resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), true));
// 解析:@ModelAttribute(required = true)
resolvers.add(new ServletModelAttributeMethodProcessor(true));

return resolvers;
}
...
}

一些使用Tricky

调整解析器的顺序

在一次使用spring security的开发中,定义的UserDetials实现类在实现UserDetails的同时还是实现了一个Account接口,在使用时,希望实现如下的效果。

1
public void doSomething(@AuthenticationPrincipal Account accout) {}

但因为同时使用了,spring-data,spring-data提供的ProxyingHandlerMethodArgumentResolver会在AuthenticationPrincipalArgumentResolver前面对Account进行注入处理。ProxyingHandlerMethodArgumentResolver 会拦截掉所有非org.springframework中定义的接口,并尝试赋值。为了能够正常赋值给Account,需要调整两者的位置。实现如下:

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
38
39
40
import java.util.LinkedList;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver;
import org.springframework.stereotype.Component;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter;

/**
* 将 AuthenticationPrincipalArgumentResolver 移到最前面,如果不做调整,
* 会因为ProxyingHandlerMethodArgumentResolver在AuthenticationPrincipalArgumentResolver前面,
* 导致 @AuthenticationPrincipal Account account 无法注入
*/
public class ArgumentResolverBeanPostProcessor implements BeanPostProcessor {

private static final String BEAN_REQUEST_MAPPING_HANDLER_ADAPTER = "requestMappingHandlerAdapter";

@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {

if (beanName.equals(BEAN_REQUEST_MAPPING_HANDLER_ADAPTER)) {

RequestMappingHandlerAdapter adapter = (RequestMappingHandlerAdapter)bean;
List<HandlerMethodArgumentResolver> argumentResolvers = adapter.getArgumentResolvers();

LinkedList<HandlerMethodArgumentResolver> resolversAdjusted = new LinkedList<>(argumentResolvers);
argumentResolvers.stream().forEach(r -> {
if (AuthenticationPrincipalArgumentResolver.class.isInstance(r)) {
resolversAdjusted.addFirst(r);
} else {
resolversAdjusted.add(r);
}
});
adapter.setArgumentResolvers(resolversAdjusted);
}
return bean;
}
}
CATALOG
  1. 1. 写在前面
  2. 2. 自定义参数解析器
    1. 2.1. 实现效果
    2. 2.2. 实现和配置
  3. 3. Spring提供解析器
  4. 4. 一些使用Tricky
    1. 4.1. 调整解析器的顺序