Spring 加载Controller逻辑的源码笔记

本文详细解析了Spring MVC中Controller的加载过程,包括关键方法org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#initHandlerMethods的具体实现,以及如何通过isHandler方法判断Controller的存在。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#initHandlerMethods 进行加载Controller:

protected void initHandlerMethods() {
		if (logger.isDebugEnabled()) {
			logger.debug("Looking for request mappings in application context: " + getApplicationContext());
		}
		String[] beanNames = (this.detectHandlerMethodsInAncestorContexts ?
				BeanFactoryUtils.beanNamesForTypeIncludingAncestors(getApplicationContext(), Object.class) :
				getApplicationContext().getBeanNamesForType(Object.class));

		for (String beanName : beanNames) {
			if (!beanName.startsWith(SCOPED_TARGET_NAME_PREFIX)) {
				Class<?> beanType = null;
				try {
					beanType = getApplicationContext().getType(beanName);
				}
				catch (Throwable ex) {
					// An unresolvable bean type, probably from a lazy bean - let's ignore it.
					if (logger.isDebugEnabled()) {
						logger.debug("Could not resolve target class for bean with name '" + beanName + "'", ex);
					}
				}
				if (beanType != null && isHandler(beanType)) {  //isHandler 是重点方法,判断是否是Controller
detectHandlerMethods(beanName); } } } handlerMethodsInitialized(getHandlerMethods()); }

 org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping#isHandler 源码如下:

	/**
	 * {@inheritDoc}
	 * Expects a handler to have a type-level @{@link Controller} annotation.
	 */
	@Override
	protected boolean isHandler(Class<?> beanType) {
		return (AnnotatedElementUtils.hasAnnotation(beanType, Controller.class) ||
				AnnotatedElementUtils.hasAnnotation(beanType, RequestMapping.class));
	}  

 

isHandler 进行判断是否是有Controller或者RequestMapping注解,如果有的话就开始进行映射Controller的方法。
具体映射逻辑在org.springframework.web.servlet.handler.AbstractHandlerMethodMapping#detectHandlerMethods中。

 

转载于:https://www.cnblogs.com/leodaxin/p/8387599.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值