關於SpringMVC在Controller層方法的參數解析詳解
使用版本:
spring-boot: 2.1.6.RELEASE
sping: 5.1.8.RELEASE
java: openjdk 11.0.13
自定義參數解析器
為瞭能夠實現自定義參數解析器,隻需要實現 HandlerMethodArgumentResolver 並將添加到 WebMvcConfigurer#addArgumentResolvers 即可。
實現效果
下面以添加一個獲取請求頭的 client-type 參數為例進行是實現。定義註解 @ClientTypeMark 以及enum ClientType ,用於註入header中的值。
@Target({ElementType.PARAMETER}) @Retention(RetentionPolicy.RUNTIME) @Documented public @interface ClientTypeMark { }
public enum ClientType { WEB, MOBILE, UNKNOWN ; }
最終實現的效果為在Controller的方法中,可以按照如下實現使用。
@RestController @RequestMapping("/client") public class ClientTypeEndpoint { @GetMapping("/cur") public ClientType getCurClientType(@ClientTypeMark ClientType clientType) { return clientType; } }
實現和配置
按照如下方法實現 HandlerMethodArgumentResolver ,用於解析header中的 client-type 並轉化為 ClientType 。
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; } } }
為瞭使得配置能夠生效,可以按照如下的方法添加解析器。
@Configuration public class WebMvcConfig implements WebMvcConfigurer { @Override public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) { // 解析@CurUserId註解的參數 argumentResolvers.add(new CurClientTypeMethodArgumentResolver()); } }
至此,自定義參數解析器的工作就完成瞭。
Spring提供解析器
當你完成上面的自定義解析器的時候,大體就能知道Spring在Controller層的其他參數解析都是怎麼實現的瞭。
如下是Spring Mvc默認的一些參數解析器。
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 接口,在使用時,希望實現如下的效果。
public void doSomething(@AuthenticationPrincipal Account accout) {}
但因為同時使用瞭,spring-data,spring-data提供的 ProxyingHandlerMethodArgumentResolver 會在 AuthenticationPrincipalArgumentResolver 前面對Account進行註入處理。ProxyingHandlerMethodArgumentResolver 會攔截掉所有非org.springframework中定義的 接口 ,並嘗試賦值。為瞭能夠正常賦值給Account,需要調整兩者的位置。實現如下:
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; } }
總結
到此這篇關於SpringMVC在Controller層方法的參數解析的文章就介紹到這瞭,更多相關SpringMVC在Controller層方法參數內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!
推薦閱讀:
- SpringBoot自定義註解實現Token校驗的方法
- SpringMVC 參數綁定相關知識總結
- 基於@RequestBody註解隻能註入對象和map的解決
- SpringBoot全局Controller返回值格式統一
- 如何將Set直接轉成數組