写在前面 使用版本:
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) { 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 { ... private List<HandlerMethodArgumentResolver> getDefaultArgumentResolvers () { List<HandlerMethodArgumentResolver> resolvers = new ArrayList<>(); resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), false )); resolvers.add(new RequestParamMapMethodArgumentResolver()); resolvers.add(new PathVariableMethodArgumentResolver()); resolvers.add(new PathVariableMapMethodArgumentResolver()); resolvers.add(new MatrixVariableMethodArgumentResolver()); resolvers.add(new MatrixVariableMapMethodArgumentResolver()); resolvers.add(new ServletModelAttributeMethodProcessor(false )); resolvers.add(new RequestResponseBodyMethodProcessor(getMessageConverters(), this .requestResponseBodyAdvice)); resolvers.add(new RequestPartMethodArgumentResolver(getMessageConverters(), this .requestResponseBodyAdvice)); resolvers.add(new RequestHeaderMethodArgumentResolver(getBeanFactory())); resolvers.add(new RequestHeaderMapMethodArgumentResolver()); resolvers.add(new ServletCookieValueMethodArgumentResolver(getBeanFactory())); resolvers.add(new ExpressionValueMethodArgumentResolver(getBeanFactory())); resolvers.add(new SessionAttributeMethodArgumentResolver()); resolvers.add(new RequestAttributeMethodArgumentResolver()); resolvers.add(new ServletRequestMethodArgumentResolver()); resolvers.add(new ServletResponseMethodArgumentResolver()); resolvers.add(new HttpEntityMethodProcessor(getMessageConverters(), this .requestResponseBodyAdvice)); resolvers.add(new RedirectAttributesMethodArgumentResolver()); resolvers.add(new ModelMethodProcessor()); resolvers.add(new MapMethodProcessor()); resolvers.add(new ErrorsMethodArgumentResolver()); resolvers.add(new SessionStatusMethodArgumentResolver()); resolvers.add(new UriComponentsBuilderMethodArgumentResolver()); if (getCustomArgumentResolvers() != null ) { resolvers.addAll(getCustomArgumentResolvers()); } resolvers.add(new RequestParamMethodArgumentResolver(getBeanFactory(), 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;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; } }