SpringMVC--@RequestMapping注解标注方法解析
SpringMVC--@RequestMapping注解标注方法解析
本文是基于springboot进行源码追踪分析
问题
@RequestMapping注释的类及方法,Spring是何时,何种方式解析成url与方法的映射关系的?
背景
@RequestMapping注解的解析识别工作是由RequestMappingHandlerMapping类去完成的,会生成对应的RequestMappingInfo实例RequestMappingHandlerMapping类的位置是在org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.EnableWebMvcConfiguration通过@Bean注解声明的org.springframework.context.support.AbstractApplicationContext#invokeBeanFactoryPostProcessors方法解析通过@Bean标记的方法,将对应对象转换为org.springframework.context.annotation.ConfigurationClassBeanDefinitionReader.ConfigurationClassBeanDefinition注册到org.springframework.beans.factory.support.DefaultListableBeanFactoryorg.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons方法中实例化对象,并在org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods方法中调用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#afterPropertiesSet方法实现@RequestMapping注解类及方法的解析与注册
org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration中定义了WEB MVC相关的自动配置类,就比如org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping、org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter等等的实例化,
解析
类继承图

过程
在初始化RequestMappingHandlerMapping对象的时候,因为实现了org.springframework.beans.factory.InitializingBean#afterPropertiesSet方法,所以会调用org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods方法时,会调用RequestMappingHandlerMapping#afterPropertiesSet方法。
// RequestMappingHandlerMapping类中相关代码
public void afterPropertiesSet() {
this.config = new RequestMappingInfo.BuilderConfiguration();
this.config.setTrailingSlashMatch(useTrailingSlashMatch());
this.config.setContentNegotiationManager(getContentNegotiationManager());
if (getPatternParser() != null) {
this.config.setPatternParser(getPatternParser());
Assert.isTrue(!this.useSuffixPatternMatch && !this.useRegisteredSuffixPatternMatch,
"Suffix pattern matching not supported with PathPatternParser.");
}
else {
this.config.setSuffixPatternMatch(useSuffixPatternMatch());
this.config.setRegisteredSuffixPatternMatch(useRegisteredSuffixPatternMatch());
this.config.setPathMatcher(getPathMatcher());
}
// 调用父类的方法进行具体的解析
super.afterPropertiesSet();
}
在自身类的重写方法中进行了一系列的配置,同时调用了父类(org.springframework.web.servlet.handler.AbstractHandlerMethodMapping)的afterPropertiesSet方法,而具体的解析方法就在父类中。
// AbstractHandlerMethodMapping中相关代码
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)) {
//处理每个可能的bean
processCandidateBean(beanName);
}
}
handlerMethodsInitialized(getHandlerMethods());
}
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);
}
}
// beanType上是否由@Controller或者@RequestMapping,如果有则说明是一个待解析的RequestMappingInfo
if (beanType != null && isHandler(beanType)) {
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);
//获取该handler内所有的Method与RquestMappingInfo映射关系
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));
}
else if (mappingsLogger.isDebugEnabled()) {
mappingsLogger.debug(formatMappings(userType, methods));
}
methods.forEach((method, mapping) -> {
Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
//按method将RequestMappingInfo进行注册
registerHandlerMethod(handler, invocableMethod, mapping);
});
}
}
在AbstractHandlerMethodMapping#detectHandlerMethods方法中,获取当前bean的所有method与RequestMapping映射关系,并进行注册。
现在继续看AbstractHandlerMethodMapping#getMappingForMethod,根据方法名即可猜测,这里就是通过method获取RequestMappingInfo,具体的实现方法在RequestMappingHandlerMapping#createRequestMappingInfo
// org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#getMappingForMethod实现代码
/**
* Uses method and type-level @{@link RequestMapping} annotations to create
* the RequestMappingInfo.
* @return the created RequestMappingInfo, or {@code null} if the method
* does not have a {@code @RequestMapping} annotation.
* @see #getCustomMethodCondition(Method)
* @see #getCustomTypeCondition(Class)
*/
@Override
@Nullable
protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
// 根据method创建对应的RquestMappingInfo
RequestMappingInfo info = createRequestMappingInfo(method);
if (info != null) {
// 如果方法所在类上也标注了@RequestMapping,则创建类对应的RequestMappingInfo
RequestMappingInfo typeInfo = createRequestMappingInfo(handlerType);
if (typeInfo != null) {
// 将类与方法的requestMappingInfo进行合并,可以理解为获取完整的url路径
info = typeInfo.combine(info);
}
String prefix = getPathPrefix(handlerType);
if (prefix != null) {
info = RequestMappingInfo.paths(prefix).options(this.config).build().combine(info);
}
}
// 返回完整url的RequestMappingInfo对象
return info;
}
获取到对应的RequestMappingInfo之后,就需要进行注册了,下面看注册逻辑org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#registerHandlerMethod
public void register(T mapping, Object handler, Method method) {
this.readWriteLock.writeLock().lock();
try {
// 根据方法生成对应的HandlerMethod,包含了method对应的bean实例,对应的method
HandlerMethod handlerMethod = createHandlerMethod(handler, method);
// 校验url路径是否有重复,如果重复会抛出异常
validateMethodMapping(handlerMethod, mapping);
Set<String> directPaths = AbstractHandlerMethodMapping.this.getDirectPaths(mapping);
for (String path : directPaths) {
this.pathLookup.add(path, mapping);
}
String name = null;
if (getNamingStrategy() != null) {
name = getNamingStrategy().getName(handlerMethod, mapping);
addMappingName(name, handlerMethod);
}
CorsConfiguration corsConfig = initCorsConfiguration(handler, method, mapping);
if (corsConfig != null) {
corsConfig.validateAllowCredentials();
this.corsLookup.put(handlerMethod, corsConfig);
}
//MappingRegistration包含RequestMappingInfo、HandlerMethod等
//Map<T, MappingRegistration<T>> registry = new HashMap<>();
this.registry.put(mapping,
new MappingRegistration<>(mapping, handlerMethod, directPaths, name, corsConfig != null));
}
finally {
this.readWriteLock.writeLock().unlock();
}
}
总结
契机:给需要暴漏接口的方法、类上添加
@RequestMapping注解时机:由于
org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping间接实现了org.springframework.beans.factory.InitializingBean#afterPropertiesSet方法,所以在RequestMappingHandlerMapping对象初始化的时候,会调用自身的org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#afterPropertiesSet方法,自身进行一系列配置之后,就会调用父类org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#afterPropertiesSet的方法进行@RequestMapping标注方法的解析解析:主体流程都是在
AbstractHandlerMethodMapping类中的方法,具体的实现通过抽象方法的形式让子类RequestMappingHandlerMapping进行实现。具体根据method生成对应的RequestMappingInfo是在RequestMappingHandlerMapping类中的方法org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#getMappingForMethod。过程中会先解析标注了@RequestMapping的方法,生成方法对应的RequestMappingInfo实例;如果方法所在的类上也有@RequestMapping标注的注解,生成类对应的RequestMappingInfo实例,然后将两者进行合并,也就是生成完整的url映射对象注册:在解析完所有的方法之后,将
RequestMappingInfo进行注册,注册容器位于AbstractHandlerMethodMapping类中,容器为MappingRegistry mappingRegistry = new MappingRegistry(),而MappingRegistry中实际存储的容器为Map<T, MappingRegistration<T>> registry = new HashMap<>()。其中key为对应的RequestMappingInfo,value为MappingRegistration,其中MappingRegistration包含了RequestMappingInfo、HandlerMethod
SpringMVC--@RequestMapping注解标注方法解析的更多相关文章
- SpringMVC RequestMapping注解
1.@RequestMapping 除了修饰方法,还可以修饰类 2.类定义处:提供初步的请求映射信息.相对于WEB应用的根目录 方法处:提供进一步细分映射信息 相对于类定义处的URL.若类定义处未 ...
- SpringMVC @RequestMapping注解详解
@RequestMapping 参数说明 value:定义处理方法的请求的 URL 地址.(重点) method:定义处理方法的 http method 类型,如 GET.POST 等.(重点) pa ...
- 超详细 SpringMVC @RequestMapping 注解使用技巧
@RequestMapping 是 Spring Web 应用程序中最常被用到的注解之一.这个注解会将 HTTP 请求映射到 MVC 和 REST 控制器的处理方法上. 在这篇文章中,你将会看到 @R ...
- springMVC的注解@PathVariable是什么?详情及用法解析
在路由中定义变量规则后,通常我们需要在处理方法(也就是@RequestMapping注解的方法)中获取这个URL变量的具体值,并根据这个值(例如用户名)做相应的操作,Spring MVC提供的@Pat ...
- springMVC的注解详解
springmvc常用注解标签详解 1.@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业 ...
- springmvc常用注解标签详解
1.@Controller 在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层处理之后封装成一个Model ...
- springmvc常用注解标签详解【转】
转载自:http://www.cnblogs.com/leskang/p/5445698.html 1.@Controller 在SpringMVC 中,控制器Controller 负责处理由Disp ...
- 一 : springmvc常用注解
springmvc常用注解详解1.@Controller在SpringMVC 中,控制器Controller 负责处理由DispatcherServlet 分发的请求,它把用户请求的数据经过业务处理层 ...
- 转:springmvc常用注解标签详解
Spring5:@Autowired注解.@Resource注解和@Service注解 - IT·达人 - 博客园--这篇顺序渐进,讲得超级好--此人博客很不错http://www.cnblogs.c ...
随机推荐
- Linux系统下,Redis的安装与启动
1.安装Redis之前,我们先介绍下Redis: (1)Redis是什么?都有哪些特点? 概念:Redis (REmote DIctionary Server) 是用 C 语言开发的一个开源的高性能键 ...
- Redis 事务支持 ACID 么?
腾讯面试官:「数据库事务机制了解么?」 「内心独白:小意思,不就 ACID 嘛,转眼一想,我面试的可是技术专家,不会这么简单的问题吧」 程许远:「balabala-- 极其自信且从容淡定的说了一通.」 ...
- Android过时方法替代
managedQuery替换为cursorLoader example: uri = data.getData(); String[] proj = {MediaStore.Images.Media. ...
- MRCTF2020 套娃
MRCTF2020套娃 打开网页查看源代码 关于$_SERVER['QUERY_STRING']取值,例如: http://localhost/aaa/?p=222 $_SERVER['QUERY_S ...
- 白嫖党的福音!!!全新的Java300集视频(2022版)来了!
它来了它来了,经过一年时间的沉淀, [尚学堂]高淇Java300集完整版正式发布啦! 应广大网友和尚学堂忠实的孜孜学子以及听众朋友的要求,尚学堂在去年十月份就把预计在2022年发布的Java300集提 ...
- 如何获取Repeater行号(索引)、记录总数?
Repeater控件想必搞ASP.NET开发的人,基本上都到了用的炉火纯青的地步了.今个又吃了懒的亏,翻了好几个项目的代码都没找到如何获取Repeater记录总数的代码来,又Google了半天难得从老 ...
- Activity Fragment Service生命周期图
service的生命周期,从它被创建开始,到它被销毁为止,可以有两条不同的路径: A started service 被开启的service通过其他组件调用 startService()被创建. 这种 ...
- presence_of_element_located对比visibility_of_element_located
presence_of_element_located和visibility_of_element_located都是selenium里判断元素展示的方法,相信做ui自动化的小伙伴一定被这俩困扰过,本 ...
- linux文件系统讲解(一)
首先拿个一个硬盘,不能直接使用,要进行分区,比如下面的一块内存: 如果要进行分区,那么怎么分区,所以要有一个内存,用来保存怎么分区的信息,该块内存的名字叫启动块(BootBlock),他的大小是固定的 ...
- Linux深入探索01-stty与键盘信号
----- 最近更新[2021-12-20]----- 一.简介 最初的 Unix 设定假定人们使用终端连接主机计算机.30多年过去后,情况依然如此,即便是在自己的PC机上运行Unix.多年以来,终端 ...