在自定义springmvc apiversion注解的过程中,由于对springmvc处理请求分发的不理解,便粗略过了一边流程(相信半个月后我就忘记了)
参考文章:
https://blog.csdn.net/roberts939299/article/details/73260485
https://www.jianshu.com/p/fd4a61c47b86
【仅供参考】 有理解错误的地方请指出
在自定义注解的过程中涉及到了RequestMappingHandlerMapping,RequestCondition两个类。衍生出了springMvc处理请求分发的主要及各类:
RequestMappingInfo:当spring启动过程中创建处理器映射对象时,会寻找所有被@Controller注解的类中被@RequestMapping注解的方法对象,然后解析方法对象的@RequestMapping注解,把解析结果封装成RequestMappingInfo对象,也就是说RequestMappingInfo对象是用来装载请求处理方法的配置信息的,每个请求处理方法对象都会对应一个RequestMappingInfo对象。
@RequestMapping注解一共有6个配置项,这6个配置项其实就是6种过滤器,限定了请求处理方法对象可处理的请求,通过这6种过滤条器把方法不能处理的请求都pass掉。
- PatternsRequestCondition(模式请求路径过滤器)
2. ParamsRequestCondition(请求参数过滤器)
3. HeadersRequestCondition(头字段过滤器)
4.RequestMethodsRequestCondition (请求方法过滤器)
5.ProducesRequestCondition(应答媒体类型过滤器)
6.ConsumesRequestCondition(请求媒体类型过滤器)
HandlerMapping:定义根据请求获取处理当期请求的HandlerChain的getHandler方法,其中包括实际处理逻辑的handler对象和拦截器。
AbstractHandlerMapping: 实现HandlerMapping接口的抽象类,在getHandler方法实现了拦截器的初始化和handler对象获取,其中获取handler对象的。
AbstractHandlerMethodMapping<T>: 继承AbstractHandlerMapping,定义了method handler映射关系,每一个method handler都一个唯一的T关联 。
RequestMappingInfoHandlerMapping: 继承AbstractHandlerMethodMapping<RequestMappingInfo>
,定义了RequestMappingInfo与method handler的关联关系。
RequestMappingHandlerMapping继承了RequestMappingInfoHandlerMapping,处理方法的@ReqeustMapping注解,将其与method handler与@ReqeustMapping注解构建的RequestMappingInfo关联。
由于实现与继承关系都来自接口HandlerMapping(映射处理器),所以下文统称以上AbstractHandlerMapping等类为HandlerMapping。
RequestMappingInfo的初始化:
从RequestMappingInfo的介绍中得知,将访问url映射到controller方法,是由RequestMappingInfo中的信息完成的,一个controller方法对应一个RequestMappingInfo。初始化RequestMappingInfo在HandlerMapping定义并在AbstractHandlerMethodMapping中实现:
/**
* 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());
}
/**
* Look for handler methods in the specified handler bean.
* @param handler either a bean name or an actual handler instance
* @see #getMappingForMethod
*/
protected void detectHandlerMethods(Object handler) {
Class<?> handlerType = (handler instanceof String ?
obtainApplicationContext().getType((String) handler) : handler.getClass());
if (handlerType != null) {
Class<?> userType = ClassUtils.getUserClass(handlerType);
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(formatMappings(userType, methods));
}
methods.forEach((method, mapping) -> {
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
@Nullable
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
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);
}
detectHandlerMethods跟踪到最后,在RequestMappingHandlerMapping中有createRequestMappingInfo方法,用于通过@RequestMapping注解生成RequestMappingInfo
@Nullable
private RequestMappingInfo createRequestMappingInfo(AnnotatedElement element) {
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);
}
protected RequestMappingInfo createRequestMappingInfo(
RequestMapping requestMapping, @Nullable RequestCondition<?> customCondition) {
RequestMappingInfo.Builder builder = RequestMappingInfo
.paths(resolveEmbeddedValuesInPatterns(requestMapping.path()))
.methods(requestMapping.method())
.params(requestMapping.params())
.headers(requestMapping.headers())
.consumes(requestMapping.consumes())
.produces(requestMapping.produces())
.mappingName(requestMapping.name());
if (customCondition != null) {
builder.customCondition(customCondition);
}
return builder.options(this.config).build();
}
这里注意getCustomMethodCondition方法,在自定义handlerMapping会使用到。
处理请求分发的流程:
详情看转载文章,这里提取一些文章没讲到的点:
- 一个DispatcherServlet拥有多个handlerMapping等
/** List of HandlerMappings used by this servlet. */
@Nullable
private List<HandlerMapping> handlerMappings;
/** List of HandlerAdapters used by this servlet. */
@Nullable
private List<HandlerAdapter> handlerAdapters;
/** List of HandlerExceptionResolvers used by this servlet. */
@Nullable
private List<HandlerExceptionResolver> handlerExceptionResolvers;
- RequestMappingInfo类中封装了过滤器Condition,用于筛选出合适的RequestMappingInfo。
public final class RequestMappingInfo implements RequestCondition<RequestMappingInfo> {
@Nullable
private final String name;
private final PatternsRequestCondition patternsCondition;
private final RequestMethodsRequestCondition methodsCondition;
private final ParamsRequestCondition paramsCondition;
private final HeadersRequestCondition headersCondition;
private final ConsumesRequestCondition consumesCondition;
private final ProducesRequestCondition producesCondition;
private final RequestConditionHolder customConditionHolder;
}
- 有些看文章思路不清晰的地方,跟进去源码看会好懂很多,这篇文章让我受益匪浅,半个月后我再来看一遍哈哈哈哈。