程序员程序园Java Blog

SpringMVC【二】HandlerMapping

2019-04-28  本文已影响17人  爪哇部落格

\color{red}{码字不易,欢迎大家转载,烦请注明出处;谢谢配合}

上节我们对DispatcherServlet如何串起请求的流程进行了梳理,本文将针对其中的HandlerMapping进行研究。

HandlerMapping

我们知道HandlerMapping是一个接口,只有一个getHandler(HttpServletRequest request)接口方法需要子类实现,返回HandlerExecutionChain对象,HandlerExecutionChain具体包含Handler对象以及Interceptors集合;如下是具体代码:

public interface HandlerMapping {
    /**省略部分常量**/
    @Nullable
    HandlerExecutionChain getHandler(HttpServletRequest request) throws Exception;
}

-----------------------------------------分割线------------------------------------
public class HandlerExecutionChain {
    /**handler对象**/
    private final Object handler;

    @Nullable
    private HandlerInterceptor[] interceptors;
    /**拦截器集合**/
    @Nullable
    private List<HandlerInterceptor> interceptorList;
}

我们再通过如下类图了解HandlerMapping的继承实现结构:

HandlerMapping

AbstractHandlerMapping

我们先看HandlerMapping的抽象子类AbstractHandlerMapping是如何实现getHandler接口的:

getHandler 抽象方法以及包装过程

那么getHandlerInternal具体是如何实现的呢,我们来看看AbstractHandlerMapping的两个子类;

AbstractHandlerMapping子类

AbstractHandlerMapping子类AbstractHandlerMethodMapping

获取HandlerMethod过程

AbstractHandlerMethodMapping实现getHandlerInternal方法

getHandlerInternal

我们一起来梳理一下获取getHandlerInternal的过程:
1.先根据请求获取lookupPath
2.根据lookupPath以及request调用lookupHandlerMethod
3.Match是抽象类的一个内部类,用于记录Mapping跟HandlerMethod对应关系
4.具体的是否匹配在调用addMatchingMappings时由子类实现getMatchingMapping方法来确定
5.如果匹配的match不唯一,由子类利用getMappingComparator方法返回comparator来决定。
6.返回bestMatch.handlerMethod

HandlerMethod初始化过程

我们通过以上代码了解到如何HandlerMethod,那么mappingRegistry是如何初始化的呢?

AbstractHandlerMethodMapping实现了InitializingBean接口,初始化时会调用afterPropertiesSet方法,此方法便是入口,以下是代码流程:

@Override
public void afterPropertiesSet() {
/**1.调用初始化方法**/
initHandlerMethods();
}

/**初始化HandlerMethod**/
protected void initHandlerMethods() {
/**2.getCandidateBeanNames获取候选的BeanName**/
/**遍历所有候选beanName**/
for (String beanName : getCandidateBeanNames()) {
    if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
          /**3.处理候选的Beans**/            
          processCandidateBean(beanName);
    }
}

handlerMethodsInitialized(getHandlerMethods());
}

/**获取候选的BeanName**/
protected String[] getCandidateBeanNames() {
return (this.detectHandlerMethodsInAncestorContexts ?
        BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
        obtainApplicationContext().getBeanNamesForType(Object.class));
}

/**处理候选的Beans**/
protected void processCandidateBean(String beanName) {
Class<?> beanType = null;
try {
    beanType = obtainApplicationContext().getType(beanName);
}
catch (Throwable ex) {
    if (logger.isTraceEnabled()) {
        logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
    }
}
 /**4.isHandler抽象方法由子类实现**/
if (beanType != null && isHandler(beanType)) {
     /**5.探测HandlerMethod**/
      detectHandlerMethods(beanName);
}
}

/**抽象方法由子类实现,被Controller或RequestMapping注解标注**/
protected abstract boolean isHandler(Class<?> beanType);

/**探测HandlerMethod**/   
protected void detectHandlerMethods(Object handler) {
/**获取handler的类类型**/
Class<?> handlerType = (handler instanceof String ?
        obtainApplicationContext().getType((String) handler) : handler.getClass());

if (handlerType != null) {
    /**获取实际类类型,handlerType有可能是由CGLIB代理生成的子类**/
    Class<?> userType = ClassUtils.getUserClass(handlerType);
/**反射获取userType类的方法以及T,T泛型由子类指定**/  
    Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
            (MethodIntrospector.MetadataLookup<T>) method -> {
                try {
                    /**6.抽象方法,由子类实现,返回该方法的Mapping信息**/
                    return getMappingForMethod(method, userType);
                }
                catch (Throwable ex) {
                    throw new IllegalStateException("Invalid mapping on handler class [" +
                            userType.getName() + "]: " + method, ex);
                }
            });
    if (logger.isTraceEnabled()) {
        logger.trace(formatMappings(userType, methods));
    }
    methods.forEach((method, mapping) -> {
        Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
        /**7.注册Handler,method,mapping到MappingRegistry**/
        registerHandlerMethod(handler, invocableMethod, mapping);
    });
}
}

/**注册Handler,method,mapping到MappingRegistry**/
protected void registerHandlerMethod(Object handler, Method method, T mapping) {
    this.mappingRegistry.register(mapping, handler, method);
}

image.png

我们梳理一下注册的流程:
1.初始化时调用initHandlerMethods方法
2.获取候选beanNames
3.处理候选beanName
4.由子类isHandler方法完成是否handler判断
5.探测HandlerMethods
6.由子类返回getMappingForMethod的Mapping信息
7.注册Handler,method,mapping到MappingRegistry

AbstractHandlerMethodMapping继承关系如下:


AbstractHandlerMethodMapping子类

RequestMappingHandlerMappingisHandler方法实现

@Override
protected boolean isHandler(Class<?> beanType) {
    return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
            AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
}

RequestMappingHandlerMapping中根据一个类是否有@Controller或@RequestMapping注解来判断是否是Handler

而AbstractHandlerMethodMapping的另一个子类RequestMappingInfoHandlerMapping则指定了泛型RequestMappingInfo,前文中所讲的T的真身便是RequestMappingInfo了,它具体就是解析了@RequestMapping注解中的值。

// @RequestMapping 中的信息
private final String name;
// @RequestMapping 中 value|path 的解析器,
private final PatternsRequestCondition patternsCondition;
// @RequestMapping 中 RequestMethod 的解析器
private final RequestMethodsRequestCondition methodsCondition;
// @RequestMapping 中 param 的解析器
private final ParamsRequestCondition paramsCondition;
// @RequestMapping 中 headers 的解析器
private final HeadersRequestCondition headersCondition;
// @RequestMapping 中 consumes 的解析器
private final ConsumesRequestCondition consumesCondition;
// @RequestMapping 中 produces 的解析器
private final ProducesRequestCondition producesCondition;
// RequestCondition 的 holder
private final RequestConditionHolder customConditionHolder;

AbstractHandlerMapping子类AbstractUrlHandlerMapping

我们知道AbstractHandlerMapping有两个关键的子类一个是AbstractMethodHandlerMapping,而另一个则是AbstractUrlHandlerMapping,同样的先看getHandlerInternal实现

获取Handler过程

getHandlerInternal lookupHandler buildPathExposingHandler

我们梳理一下获取Handler的过程:
1.调用lookupHandler
2.根据urlPath获取,不为空则构建Handler返回
3.为空则根据pattern获取,获取到最匹配的则构建返回
4.如果没有获取到则处理默认Handler,如:RootHandler,DefaultHandler等
5.返回Handler

Handler初始化过程

同样的我们了解清楚获取的过程以后,一起来学习一下初始化Handler的过程,我们没有找到初始化相关的initXX方法,当时发现了registerHandler方法,我们大胆的猜想,它可能是有子类初始化时调用的,我们先看这个方法具体的内容:

registerHandler

AbstractUrlHandlerMapping继承关系如下


AbstractUrlHandlerMapping继承关系
分支子类AbstractDetectingUrlHandlerMapping

先看AbstractDetectingUrlHandlerMapping 初始化过程

initApplicationContext detectHandlers determineUrlsForHandler

AbstractDetectingUrlHandlerMapping子类BeanNameUrlHandlerMapping实现determineUrlsForHandler方法

BeanNameUrlHandlerMapping
分支子类SimpleUrlHandlerMapping
initApplicationContext registerHandlers

总结

1.了解HandlerMapping的核心子类AbstractHandlerMapping
2.其次了解HandlerExecutionChain的结构Handler对象+ Interceptors
3.了解AbstractHandlerMapping 的两个分支子类AbstractHandlerMethodMapping,AbstractUrlHandlerMapping
4.清楚获取Handler 以及 注册 Handler的过程

上一篇 下一篇

猜你喜欢

热点阅读