SpringBoot源码-mvc工作流程(上)

SpringMVC 这么重要,怎么能错过,搞起~

 在初始化容器的时候,会把url与类方法的映射关系注册进去,一切从AbstractHandlerMethodMapping 类说起,找到该类下的initHandlerMethods() 方法,代码如下:
protected void initHandlerMethods() {
    // 获取容器初始化的bean,遍历
    for (String beanName : getCandidateBeanNames()) {
        if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
            processCandidateBean(beanName);
        }
    }
    handlerMethodsInitialized(getHandlerMethods());
}

点击进入processCandidateBean()方法,核心代码如下:

protected void processCandidateBean(String beanName) {
    Class beanType = null;
    // 获取bean的类型
    beanType = obtainApplicationContext().getType(beanName);
    // 如果有注解 @Controller 或 @RequestMapping,则进入
    if (beanType != null && isHandler(beanType)) {
        detectHandlerMethods(beanName);
    }
}

isHandler()方法很简单,就是判断beanType是否有 @Controller 或 @RequestMapping 注解:

protected boolean isHandler(Class beanType) {
    return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
            AnnotatedElementUtils.hasAnnotation(beanType,equestMapping.class));
}

回到 processCandidateBean()方法,点击 detectHandlerMethods(),进入,核心代码:

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是实际是 RequestMappingInfo 类型
        Map methods = MethodIntrospector.selectMethods(userType,
        (MethodIntrospector.MetadataLookup) method -> {
            // 获取方法的映射
            return getMappingForMethod(method, userType);
        });
        
        methods.forEach((method, mapping) -> {
               Method invocableMethod =                            
               AopUtils.selectInvocableMethod(method,userType);
            // 注册方法
               registerHandlerMethod(handler, invocableMethod, mapping);
        });
    }
}

点击 getMappingForMethod()方法,核心代码:

protected RequestMappingInfo getMappingForMethod(Method method, Class handlerType) {
    // 创建方法的 RequestMappingInfo
    RequestMappingInfo info = createRequestMappingInfo(method);
    if (info != null) {
        // 创建类的 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);
        }
    }
}

点击 createRequestMappingInfo()进去,代码很简单:

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));
    // 构建 RequestMappingInfo 返回
    return (requestMapping != null ? 
            createRequestMappingInfo(requestMapping,condition) : null);
}

回到 getMappingForMethod()方法,点击 typeInfo.combine(info) 进去:

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);
}

这个方法也很简单,就是把 patterns、methods、params、headers等合并起来,构建RequestMappingInfo 返回。

我们再回到 detectHandlerMethods() 方法,找到registerHandlerMethod(),点击进入,核心代码:

public void register(T mapping, Object handler, Method method) {
    // 构建新的 handlerMethod
    HandlerMethod handlerMethod = createHandlerMethod(handler, method);
    Set 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));
}

这里有两个很重要的结构:

private final MultiValueMap pathLookup = 
                                                new LinkedMultiValueMap<>();

private final Map> nameLookup = 
                                                new ConcurrentHashMap<>();

这两个变量存储了url与类方法的关系。

看我的例子,造的两个接口:

SpringBoot源码-mvc工作流程(上)_第1张图片

pathLookup存储的结构信息:

SpringBoot源码-mvc工作流程(上)_第2张图片

nameLookup存储的结构信息:

SpringBoot源码-mvc工作流程(上)_第3张图片

各位细品,千言万语都汇聚在图中~~

你可能感兴趣的:(SpringBoot源码-mvc工作流程(上))