SpringMVC常用注解載入與處理方式詳解
一 . 前言
這一篇來看一下SpringMVC 中各個注解載入的方式和處理的時機
二 . RestController 部分
RestController 注解主要的作用是Bean的加載 , 值得關注的注解包括 : @Controller 和 @ResponseBody
而 Contoller 注解攜帶 @Component , 所以主要執(zhí)行的位置是 Bean 處理 .
在 Bean 處理過程中 , 主要是在 RequestMappingHandlerMapping 中對 @RequestMapping 進行掃描處理
//C- AbstractHandlerMethodMapping # initHandlerMethods : 一切的起點 , 開始對所有需要掃描的 Bean 進行處理 protected void initHandlerMethods() { for (String beanName : getCandidateBeanNames()) { if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) { // 后續(xù)會進行 Registry 對 Mapping 進行注冊 processCandidateBean(beanName); } } // 主要是 log 處理 , 可以重寫 handlerMethodsInitialized(getHandlerMethods()); }
總結 : RestController 主要用于把Bean注入到 Spring 體系中 , 觸發(fā) Mapping 掃描
三 . RequestMapping 部分
上面觸發(fā)了 Mapping 的加載后 , 就會通過 Registry 把 Mapping 注冊到集合中 , 先大概過一下流程
// S1 : AbstractHandlerMethodMapping # detectHandlerMethods : 逐一對Bean進行掃描處理
- MethodIntrospector.selectMethods 掃描所有的 Method , 獲取 Map<Method, T>
- methods.forEach 調用 registerHandlerMethod 對 Method 進行注冊
// S2 : AbstractHandlerMethodMapping # register : 注冊 Handler 和 Method 到各個集合中
- 這里之前說過 , 有多個 Mapping 用來保存 Handler 的映射關系
- this.mappingLookup.put(mapping, handlerMethod);
- this.urlLookup.add(url, mapping);
- this.corsLookup.put(handlerMethod, corsConfig);
// S3 : AbstractHandlerMethodMapping # lookupHandlerMethod : 對 URL 進行解析 , 尋找對應的 Mapping
- this.mappingRegistry.getMappingsByUrl(lookupPath);
S1 : @RequestMapping 注解的載入
注解在上文S1階段就已經被載入了 , 在掃描所有的Mapping的時候進行了 RequestMapping 的解析
// S1-1 : 獲取到 Mathod 之上的注解 RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class); // S1-2 : 通過 Mapping 創(chuàng)建 MappingInfo createRequestMappingInfo(requestMapping, condition) RequestMappingInfo.Builder builder = RequestMappingInfo .paths(resolveEmbeddedValuesInPatterns(requestMapping.path())) .methods(requestMapping.method()) .params(requestMapping.params()) .headers(requestMapping.headers()) .consumes(requestMapping.consumes()) .produces(requestMapping.produces()) .mappingName(requestMapping.name()); // 此處對注解上的參數進行解析 builder.options(this.config).build() // S3 : 構建 AbstractRequestCondition 細節(jié)就不看了 , 主要是構建 ParamsRequestCondition , ConsumesRequestCondition 等 放入 RequestMappingInfo 對象中
S3 : RequestMapping 的使用
// S3-1 : AbstractHandlerMethodMapping # lookupHandlerMethod : 通過 path 查詢 Mapping List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath); // S3-2 : addMatchingMappings 添加 HandlerMethod addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
以下2個圖分別是請求的匹配Condition和HandlerMethod中描述的處理類 , 這樣的集合在 S2 環(huán)節(jié)注入>>
private final Map<T, MappingRegistration<T>> registry = new HashMap<>(); private final Map<T, HandlerMethod> mappingLookup = new LinkedHashMap<>(); private final MultiValueMap<String, T> urlLookup = new LinkedMultiValueMap<>(); private final Map<String, List<HandlerMethod>> nameLookup = new ConcurrentHashMap<>(); private final Map<HandlerMethod, CorsConfiguration> corsLookup = new ConcurrentHashMap<>(); private final ReentrantReadWriteLock readWriteLock = new ReentrantReadWriteLock();
總結:RequestMapping 主要在Bean掃描時觸發(fā) >>>
- 當獲取到 Bean 中 Mehtod 時 , 會創(chuàng)建對應的 RequestMappingInfo , 存入多個集合中
- 當請求進來后 , 會在 lookupHandlerMethod 中獲取對應Method 處理類**
四 . RequestParam和PathVariable
這是最常用的2個參數傳遞方式 , 主要的加載類為 : RequestParamMethodArgumentResolver
RequestParam 處理流程
// S1 : RequestMappingHandlerAdapter # invokeAndHandle : 發(fā)起方法的調用
- 此處為參數處理的入口 , 當請求進來時 , 會代理到對應的方法 , 在代理的過程中進行處理
// S2 : InvocableHandlerMethod # getMethodArgumentValues : 循環(huán)方法中所有的參數
- getMethodArgumentValues 中會對 Bean 加載時即生成的 HandMethod 進行處理
// S3 : HandlerMethodArgumentResolverComposite # getArgumentResolver : 對所有解析類進行處理
- for 循環(huán)進行的處理
- 解析類用來解析參數上面的注解 , 判斷是否符合某種注解的解析條件
- 包括 PathVariable 等多種注解的解析
// S4 : RequestParamMethodArgumentResolver # supportsParameter : 判斷是否包含 RequestParam 注解
- 如果符合解析條件 , 把 MethodParameter 和 resolver 都放在緩存中
// S5 : RequestParamMethodArgumentResolver # resolveArgument : 對參數進行解析
PathVariable 處理流程
PathVariable 和上面的流程一樣 , 主要在 S3 進行處理
總結 :RequestParam 和 PathVariable 主要還是在實際調用 Invoke 方法時解析處理
- 調用代理方法時會對所有的參數進行解析 >> S1
- 解析通過 support + resolve 兩步完成 , 也就是策略
- 解析完成后放入 Object[] 再調用具體的 Method
五 . RequestBody 和 ResponseBody
核心加載類 : RequestResponseBodyMethodProcessor , 其實主要流程和上文比較類似 , 只不過該類在調用和返回時都有相關的調用
RequestBody
// S1 : 判斷是否需要解析 public boolean supportsParameter(MethodParameter parameter) { return parameter.hasParameterAnnotation(RequestBody.class); } // S2 : 解析數據 resolveArgument // 這里就不細說了 , 就是一個 Converters
ResponseBody
public void handleReturnValue(@Nullable Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest){} //- 返回值 , 返回類型 , Model 上下文等
開關的處理
// 問題一 : 加了 ResponseBody 后為什么可以不用跳 View
- 過去前后不分離的場景 , 通常會通過一個 View 來接收跳轉地址到對應的 HTML 頁面
- 但是加了 ResponseBody 后則可以直接返回出去
? 如何處理的 :
handleReturnValue 中 mavContainer.setRequestHandled(true) :
> 當設置了 ResponseBody 后 , view resolution is not argument
> 當后文 getModelAndView 時會根據這個參數直接返回 null
總結
- RestController 觸發(fā) Bean 的加載
- RequestMapping 加載 method 和 url 信息到集合中
- 通過 Resolver 對 Body 等任何方法上的參數進行處理 , 通過代理實現
到此這篇關于SpringMVC常用注解載入與處理方式詳解的文章就介紹到這了,更多相關SpringMVC注解載入與處理內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Spring Data JPA使用Sort進行排序(Using Sort)
本篇文章主要介紹了Spring Data JPA使用Sort進行排序(Using Sort),具有一定的參考價值,有興趣的可以了解一下2017-07-07