接上一篇
Spring MVC 核心类: HandlerMapping(二)
2.4 AbstractHandlerMethodMapping
这个类是比较常用的基础类,他定义了请求(request)到 HandlerMethod 的映射关系。
该类是泛型类,子类用这个泛型来定义详细的Request到方法之间的详细信息。所以本类需要他的子类来保存处理器(例如controller实例)的方法以及方法对应的映射。
2.4.1 内部类 MappingRegistry
在AbstractHandlerMethodMapping
基础类中定义了一个注册器用于注册所有的方法和请求的映射。这个注册器类暴露了当前访问请求的查询对应HandlerMethod
的方法。
4 个重要属性:
// 1. 记录所有可能的映射关系,包含映射对象、处理方法、直接匹配的URL(可空),映射名称(可空)
private final Map<T, MappingRegistration<T>> registry = new HashMap<>();
// 2. 记录映射对象和对应方法的Map
private final Map<T, HandlerMethod> mappingLookup = new LinkedHashMap<>();
// 3. 记录直接URL的Map(没有匹配,直接URL的映射)
private final MultiValueMap<String, T> urlLookup = new LinkedMultiValueMap<>();
// 4. 名称映射Map(如果配置了通过名称匹配策略,记录名称和映射的Map)
private final Map<String, List<HandlerMethod>> nameLookup = new ConcurrentHashMap<>();
// 5. 跨域配置
private final Map<HandlerMethod, CorsConfiguration> corsLookup = new ConcurrentHashMap<>();
重要方法register
:
public void register(T mapping, Object handler, Method method) {
this.readWriteLock.writeLock().lock();
try {
// 1. 构建HandlerMethod,记录对应的Handler、方法(包含桥接方法)、参数、
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
// 2. 校验对应映射的唯一性
assertUniqueMethodMapping(handlerMethod, mapping);
this.mappingLookup.put(mapping, handlerMethod);
// 3. 查询直接用URL匹配的映射
List<String> directUrls = getDirectUrls(mapping);
for (String url : directUrls) {
this.urlLookup.add(url, mapping);
}
// 4. 如果配置了用名称策略来进行映射,记录名称和映射方法
String name = null;
if (getNamingStrategy() != null) {
name = getNamingStrategy().getName(handlerMethod, mapping);
addMappingName(name, handlerMethod);
}
CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
if (corsConfig != null) {
this.corsLookup.put(handlerMethod, corsConfig);
}
// 5. 记录所有可能的映射值
this.registry.put(mapping, new MappingRegistration<>(mapping, handlerMethod, directUrls, name));
}
finally {
this.readWriteLock.writeLock().unlock();
}
}
2.4.2 什么时候注册
AbstractHandlerMethodMapping 实现了 InitializingBean
, 在构建Bean实例后进行设置对应属性进行了回调:
/**
* Detects handler methods at initialization.
* @see #initHandlerMethods
*/
@Override
public void afterPropertiesSet() {
initHandlerMethods();
}
/**
* Scan beans in the ApplicationContext, detect and register handler methods.
* @see #getCandidateBeanNames()
* @see #processCandidateBean
* @see #handlerMethodsInitialized
*/
protected void initHandlerMethods() {
for (String beanName : getCandidateBeanNames()) {
if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
processCandidateBean(beanName);
}
}
handlerMethodsInitialized(getHandlerMethods());
}
从上面的代码中我们可以看出最终处理探测每一个Handler对象的方法是processCandidateBean
:
protected void processCandidateBean(String beanName) {
Class<?> beanType = null;
try {
beanType = obtainApplicationContext().getType(beanName);
}
catch (Throwable ex) {
// An unresolvable bean type, probably from a lazy bean - let's ignore it.
if (logger.isTraceEnabled()) {
logger.trace("Could not resolve type for bean '" + beanName + "'", ex);
}
}
if (beanType != null && isHandler(beanType)) {
// 探测所有的Hanler对应的方法
detectHandlerMethods(beanName);
}
}
protected void detectHandlerMethods(Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
Class<?> userType = ClassUtils.getUserClass(handlerType);
// 查找类所有的方法,然后判断是否需要进行映射注册。
// 其中通过调用getMappingForMethod方法进行判断是否需要映射处理,
// getMappingForMethod 方法留给子类进行扩展
Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
(MethodIntrospector.MetadataLookup<T>) method -> {
try {
return getMappingForMethod(method, userType);
}
catch (Throwable ex) {
throw new IllegalStateException("Invalid mapping on handler class [" +
userType.getName() + "]: " + method, ex);
}
});
if (logger.isTraceEnabled()) {
logger.trace("Mapped " + methods.size() + " handler method(s) for " + userType + ": " + methods);
}
methods.forEach((method, mapping) -> {
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
// 注册对应的方法,触发内部MappingRegistry进行注册
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
2.4.3 通过Request查找Handler
@Override
protected HandlerMethod getHandlerInternal(HttpServletRequest request) throws Exception {
String lookupPath = getUrlPathHelper().getLookupPathForRequest(request);
this.mappingRegistry.acquireReadLock();
try {
HandlerMethod handlerMethod = lookupHandlerMethod(lookupPath, request);
return (handlerMethod != null ? handlerMethod.createWithResolvedBean() : null);
}
finally {
this.mappingRegistry.releaseReadLock();
}
}
具体的查找逻辑:
通过当前请求返回最优匹配的Handler方法(如果有多个匹配,返回最匹配的那一个)。如果存在两个最匹配的Handler方法,异常抛出。
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
List<Match> matches = new ArrayList<>();
// 1. 首先看看是否有直接URL的匹配,如果存在放在待处理的匹配列表中
List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
if (directPathMatches != null) {
addMatchingMappings(directPathMatches, matches, request);
}
// 2. 如果从URL匹配找不到对应的匹配的Handler,只能从所有的注册的映射中查找
if (matches.isEmpty()) {
// No choice but to go through all mappings...
addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
}
// 3. 对所有的可能的匹配进行排序,取第一个。
// 当存在两个以上的匹配,校验第一匹配和第二匹配是不是同一优先级,如果是,表面有两个同样匹配,异常抛出。
if (!matches.isEmpty()) {
Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
matches.sort(comparator);
Match bestMatch = matches.get(0);
if (matches.size() > 1) {
if (logger.isTraceEnabled()) {
logger.trace(matches.size() + " matching mappings: " + matches);
}
if (CorsUtils.isPreFlightRequest(request)) {
return PREFLIGHT_AMBIGUOUS_MATCH;
}
Match secondBestMatch = matches.get(1);
if (comparator.compare(bestMatch, secondBestMatch) == 0) {
Method m1 = bestMatch.handlerMethod.getMethod();
Method m2 = secondBestMatch.handlerMethod.getMethod();
String uri = request.getRequestURI();
throw new IllegalStateException(
"Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
}
}
handleMatch(bestMatch.mapping, lookupPath, request);
return bestMatch.handlerMethod;
}
// 4. 如果没有匹配,走无匹配处理,子类可扩展,默认返回`null`。
else {
return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
}
}
2.4.4 子类 RequestMappingInfoHandlerMapping
这个类主要定义了用RequestMappingInfo
这个映射定义来处理方法映射。RequestMappingInfo 定义来我们常用的映射条件,使用这些映射条件,可以判断是否请求是否匹配:
private final PatternsRequestCondition patternsCondition;
private final RequestMethodsRequestCondition methodsCondition;
private final ParamsRequestCondition paramsCondition;
private final HeadersRequestCondition headersCondition;
private final ConsumesRequestCondition consumesCondition;
private final ProducesRequestCondition producesCondition;
2.4.5 子类 RequestMappingHandlerMapping
这个是 RequestMappingInfoHandlerMapping 子类,这个定义来方法基本的Handler映射。
这个类重要的方法是通过方法来找映射:
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
// 创建方法级别映射信息
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
// 创建类级别的映射信息
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
// 如果存在类级别的映射,把方法级别的和类级别的两个映射合并
info = typeInfo.combine(info);
}
// 处理方法前缀,如果存在和前者方法级别的合并
String prefix = getPathPrefix(handlerType);
if (prefix != null) {
info = RequestMappingInfo.paths(prefix).build().combine(info);
}
}
return info;
}
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
// 查找 RequestMapping 注解,RequestMapping 是 GetMapping、PostMapping 等的超类
RequestMapping requestMapping = AnnotatedElementUtils.findMergedAnnotation(element, RequestMapping.class);
RequestCondition<?> condition = (element instanceof Class ?
getCustomTypeCondition((Class<?>) element) : getCustomMethodCondition((Method) element));
return (requestMapping != null ? createRequestMappingInfo(requestMapping, condition) : null);
}
从上面代码中我们可以看出,我们通常在 Controller 类中使用的 RequestMapping 配置的映射的加载逻辑:先找方法 -〉 然后类 -〉在处理前缀。