Spring Boot源码之旅二十三SpringMVC源码之RequestMappingHandlerMapping的初始化一

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

 

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

 

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

 

简单流程图

RequestMappingHandlerMapping的afterPropertiesSet

我们知道RequestMappingHandlerMapping是根据uri映射来获取相应的方法的,那这个uri是怎么来的呢,我们来看看RequestMappingHandlerMapping被初始化的时候做了什么。在RequestMappingHandlerMapping的父类AbstractHandlerMethodMapping实现了InitializingBean接口,所以在初始化的时候调用afterPropertiesSet方法,这里就是让他做初始化的地方:

AbstractHandlerMethodMapping的initHandlerMethods初始化处理器方法

这里就是获取所有容器里定义的bean名字,不是代理目标的都进行处理。

    	private static final String SCOPED_TARGET_NAME_PREFIX = "scopedTarget.";
    	
    	protected void initHandlerMethods() {
    		for (String beanName : getCandidateBeanNames()) {
    			if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {//代理目标不行,因为方法可能在代理的时候被重写了
    				processCandidateBean(beanName);
    			}
    		}
    		handlerMethodsInitialized(getHandlerMethods());
    	}

getCandidateBeanNames

可见这里是找出Object类型的,也就是所有的注册的bean名字,包括工厂bean

    	protected String[] getCandidateBeanNames() {
    		return (this.detectHandlerMethodsInAncestorContexts ?
    				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(obtainApplicationContext(), Object.class) :
    				obtainApplicationContext().getBeanNamesForType(Object.class));
    	}

processCandidateBean处理

获取类型,如果有Controller或者是RequestMapping注解的就进行方法检测,这里就显示出Controller的用途啦。

    protected void processCandidateBean(String beanName) {
    		Class<?> beanType = null;
    		try {
    			beanType = obtainApplicationContext().getType(beanName);
    		}
    		catch (Throwable ex) {
    			...
    		}
    		if (beanType != null && isHandler(beanType)) {
    			detectHandlerMethods(beanName);
    		}
    	}
isHandler是否是处理器

只有类上有Controller或者RequestMapping注解的才算是处理器。

    	@Override
    	protected boolean isHandler(Class<?> beanType) {
    		return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
    				AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
    	}
detectHandlerMethods检查处理方法

首先会获取处理器类型,然后进行方法的检查,符合要求的就注册到映射注册器中。

    protected void detectHandlerMethods(Object handler) {
    		Class<?> handlerType = (handler instanceof String ?
    				obtainApplicationContext().getType((String) handler) : handler.getClass());//如果是String就获取他的类型
    
    		if (handlerType != null) {
    			Class<?> userType = ClassUtils.getUserClass(handlerType);//获取用户定义的类型,针对动态代理类型
    			Map<Method, T> methods = MethodIntrospector.selectMethods(userType,
    					(MethodIntrospector.MetadataLookup<T>) method -> {
    						try {
    							return getMappingForMethod(method, userType);//检测每个方法,获取RequestMappingInfo
    						}
    						catch (Throwable ex) {
    							...
    						}
    					});
    			...
    			methods.forEach((method, mapping) -> {//进行映射和处理器绑定
    				Method invocableMethod = AopUtils.selectInvocableMethod(method, userType);
    				registerHandlerMethod(handler, invocableMethod, mapping);
    			});
    		}
    	}
MethodIntrospector的selectMethods搜索方法

对类进行方法的搜索,满足条件的封装成RequestMappingInfo和方法一起添加到methodMap中。

    	public static <T> Map<Method, T> selectMethods(Class<?> targetType, final MetadataLookup<T> metadataLookup) {
    		final Map<Method, T> methodMap = new LinkedHashMap<>();
    		Set<Class<?>> handlerTypes = new LinkedHashSet<>();
    		Class<?> specificHandlerType = null;
    
    		if (!Proxy.isProxyClass(targetType)) {
    			specificHandlerType = ClassUtils.getUserClass(targetType);
    			handlerTypes.add(specificHandlerType);//获取类型
    		}
    		handlerTypes.addAll(ClassUtils.getAllInterfacesForClassAsSet(targetType));//添加所有接口
    
    		for (Class<?> currentHandlerType : handlerTypes) {
    			final Class<?> targetClass = (specificHandlerType != null ? specificHandlerType : currentHandlerType);
    			//获取所有方法,进行检查,符合条件的放入methodMap中
    			ReflectionUtils.doWithMethods(currentHandlerType, method -> {
    				Method specificMethod = ClassUtils.getMostSpecificMethod(method, targetClass);
    				T result = metadataLookup.inspect(specificMethod);//就是getMappingForMethod
    				if (result != null) {
    					Method bridgedMethod = BridgeMethodResolver.findBridgedMethod(specificMethod);
    					if (bridgedMethod == specificMethod || metadataLookup.inspect(bridgedMethod) == null) {
    						methodMap.put(specificMethod, result);
    					}
    				}
    			}, ReflectionUtils.USER_DECLARED_METHODS);
    		}
    
    		return methodMap;
    	}
AbstractHandlerMethodMapping的getMappingForMethod获得方法映射

为创建方法RequestMappingInfo,再为类创建RequestMappingInfo ,进行合并返回。

    @Override
    	@Nullable
    	protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) {
    		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);
    			}
    		}
    		return info;
    	}

这里就是比较核心的地方,下篇详细讲下。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值