SpringMVC 這么重要因谎,怎么能錯(cuò)過(guò),搞起~
在初始化容器的時(shí)候肴敛,會(huì)把url與類方法的映射關(guān)系注冊(cè)進(jìn)去缰猴,一切從AbstractHandlerMethodMapping 類說(shuō)起,找到該類下的initHandlerMethods() 方法喊递,代碼如下:
protected void initHandlerMethods() {
// 獲取容器初始化的bean,遍歷
for (String beanName : getCandidateBeanNames()) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
processCandidateBean(beanName);
}
}
handlerMethodsInitialized(getHandlerMethods());
}
點(diǎn)擊進(jìn)入processCandidateBean()方法随闪,核心代碼如下:
protected void processCandidateBean(String beanName) {
Class<?> beanType = null;
// 獲取bean的類型
beanType = obtainApplicationContext().getType(beanName);
// 如果有注解 @Controller 或 @RequestMapping,則進(jìn)入
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
isHandler()方法很簡(jiǎn)單骚勘,就是判斷beanType是否有 @Controller 或 @RequestMapping 注解:
protected boolean isHandler(Class<?> beanType) {
return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
AnnotatedElementUtils.hasAnnotation(beanType,equestMapping.class));
}
回到 processCandidateBean()方法铐伴,點(diǎn)擊 detectHandlerMethods()撮奏,進(jìn)入,核心代碼:
protected void detectHandlerMethods(Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
Class<?> userType = ClassUtils.getUserClass(handlerType);
// 泛型T是實(shí)際是 RequestMappingInfo 類型
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> {
// 獲取方法的映射
return getMappingForMethod(method, userType);
});
methods.forEach((method, mapping) -> {
Method invocableMethod =
AopUtils.selectInvocableMethod(method,userType);
// 注冊(cè)方法
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
點(diǎn)擊 getMappingForMethod()方法当宴,核心代碼:
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
// 創(chuàng)建方法的 RequestMappingInfo
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
// 創(chuàng)建類的 RequestMappingInfo
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
// 合并方法和類的 @RequestMapping
info = typeInfo.combine(info);
}
String prefix = getPathPrefix(handlerType);
if (prefix != null) {
info = RequestMappingInfo.paths(prefix).options(this.config)
.build().combine(info);
}
}
}
點(diǎn)擊 createRequestMappingInfo()進(jìn)去畜吊,代碼很簡(jiǎn)單:
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
// 找到 element 的 @RequestMapping 注解
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
RequestCondition<?> condition = (element instanceof Class ?
getCustomTypeCondition((Class<?>) element) :
getCustomMethodCondition((Method) element));
// 構(gòu)建 RequestMappingInfo 返回
return (requestMapping != null ?
createRequestMappingInfo(requestMapping,condition) : null);
}
回到 getMappingForMethod()方法,點(diǎn)擊 typeInfo.combine(info) 進(jìn)去:
public RequestMappingInfo combine(RequestMappingInfo other) {
String name = combineNames(other);
PathPatternsRequestCondition pathPatterns =
(this.pathPatternsCondition != null && other.pathPatternsCondition != null ? this.pathPatternsCondition.combine(other.pathPatternsCondition) : null);
PatternsRequestCondition patterns =
(this.patternsCondition != null && other.patternsCondition != null ?
this.patternsCondition.combine(other.patternsCondition) : null);
RequestMethodsRequestCondition methods =
this.methodsCondition.combine(other.methodsCondition);
ParamsRequestCondition params =
this.paramsCondition.combine(other.paramsCondition);
HeadersRequestCondition headers =
this.headersCondition.combine(other.headersCondition);
……
return new RequestMappingInfo(name, pathPatterns, patterns,
methods, params, headers, consumes, produces, custom, this.options);
}
這個(gè)方法也很簡(jiǎn)單户矢,就是把 patterns玲献、methods、params梯浪、headers等合并起來(lái)捌年,構(gòu)建RequestMappingInfo 返回。
我們?cè)倩氐?detectHandlerMethods() 方法驱证,找到registerHandlerMethod()延窜,點(diǎn)擊進(jìn)入,核心代碼:
public void register(T mapping, Object handler, Method method) {
// 構(gòu)建新的 handlerMethod
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
Set<String> directPaths =
AbstractHandlerMethodMapping.this.getDirectPaths(mapping);
for (String path : directPaths) {
// path是 接口路徑抹锄,如 /a/b,mapping是 RequestMappingInfo
this.pathLookup.add(path, mapping);
}
String name = null;
if (getNamingStrategy() != null) {
name = getNamingStrategy().getName(handlerMethod, mapping);
// 把方法名和handlerMethod的映射添加到 nameLookup中
addMappingName(name, handlerMethod);
}
this.registry.put(mapping, new MappingRegistration<>(
mapping,handlerMethod, directPaths, name, corsConfig != null));
}
這里有兩個(gè)很重要的結(jié)構(gòu):
private final MultiValueMap<String, T> pathLookup =
new LinkedMultiValueMap<>();
private final Map<String, List<HandlerMethod>> nameLookup =
new ConcurrentHashMap<>();
這兩個(gè)變量存儲(chǔ)了url與類方法的關(guān)系荠藤。
看我的例子伙单,造的兩個(gè)接口:
pathLookup存儲(chǔ)的結(jié)構(gòu)信息:
nameLookup存儲(chǔ)的結(jié)構(gòu)信息:
各位細(xì)品,千言萬(wàn)語(yǔ)都匯聚在圖中~~