首先我们来看下AbstractHandlerMethodMapping这个类,它实现了InitializingBean接口,里面有个afterPropertiesSet()方法。这个接口是spring-beans这个组件的内容,想一想,平时使用搭建SpringMVC的时候,是不是把这个jar包也扔到项目里头了?对于spring-beans这个组件在这里就 不拓展了,我们只要知道实现了InitializingBean这个接口后,spring容器在对象实例化完后进行调用afterPropertiesSet()方法即可(注意这里是spring容器,而不是tomcat容器)。部分源码如下
public abstract class AbstractHandlerMethodMapping<T> extends AbstractHandlerMapping implements InitializingBean {
@Override
public void afterPropertiesSet() {
initHandlerMethods();
}
/**
* Scan beans in the ApplicationContext, detect and register handler methods.
*/
protected void initHandlerMethods() {
if (logger.isDebugEnabled()) {
logger.debug("Looking for request mappings in application context: " + getApplicationContext());
}
//取得容器的所有bean
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);
}
}
//isHandler()方法用于提取有@Controller或者@RequestMapping的类
if (beanType != null && isHandler(beanType)) {
detectHandlerMethods(beanName);
}
}
}
handlerMethodsInitialized(getHandlerMethods());//此处SpringMVC并未做任何实现
}
protected void detectHandlerMethods(final Object handler) {
Class<

本文详细探讨了SpringMVC中AbstractHandlerMethodMapping类的URL映射注册过程。从afterPropertiesSet()方法开始,该方法触发initHandlerMethods(),用于扫描应用上下文并注册处理方法。接着分析了isHandler()方法,用于识别@Controller或@RequestMapping注解的类。进一步,detectHandlerMethods()方法处理这些类,获取mapping和invocableMethod,分别代表URL和对应的方法。registerHandlerMethod()方法将这些信息注册,以便后续请求处理。文中还提到了MappingRegistry类中的五个Map以及它们的作用,展示了如何实现同一RequestMapping映射多个请求。最后,文章简要提及了@CrossOrigin注解在跨域处理中的应用。
最低0.47元/天 解锁文章
3473

被折叠的 条评论
为什么被折叠?



