关于springboot:SpringBoot源码mvc工作流程上

63次阅读

共计 4399 个字符,预计需要花费 11 分钟才能阅读完成。

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<Method, T> methods = MethodIntrospector.selectMethods(userType,
        (MethodIntrospector.MetadataLookup<T>) 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<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));
}

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

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

private final Map<String, List<HandlerMethod>> nameLookup = 
                                                new ConcurrentHashMap<>();

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

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

pathLookup 存储的构造信息:

nameLookup 存储的构造信息:

各位细品,一言半语都汇聚在图中~~

正文完
 0