SpringMVC源码分析(二)-URL映射的注册

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

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

​ 首先我们来看下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<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值