SpringMVC初始化HandlerMapping浅析

HttpServlet
HttpServletBean
FrameworkServlet
DispatcherServlet

以上是DispatcherServlet的继承关系


初始化HandlerMapper的方法调用过程如下:

org.springframework.web.servlet.HttpServletBean.init()
org.springframework.web.servlet.HttpServletBean.initServletBean()
org.springframework.web.servlet.FrameworkServlet.initServletBean()
org.springframework.web.servlet.FrameworkServlet.initWebApplicationContext()
org.springframework.web.servlet.FrameworkServlet.onRefresh(ApplicationContext)
org.springframework.web.servlet.DispatcherServlet.onRefresh(ApplicationContext)
org.springframework.web.servlet.DispatcherServlet.initStrategies(ApplicationContext)
org.springframework.web.servlet.DispatcherServlet.initHandlerMappings(ApplicationContext)

初始化HandlerMapper函数:

    /**
     * Initialize the HandlerMappings used by this class.
     * <p>If no HandlerMapping beans are defined in the BeanFactory for this namespace,
     * we default to BeanNameUrlHandlerMapping.
     */
    private void initHandlerMappings(ApplicationContext context) {
        this.handlerMappings = null;

        //detectAllHandlerMappings 是否找出所有HandlerMapping
        //如果不是,就只取名为“handlerMapping”的HandlerMapping
        if (this.detectAllHandlerMappings) {
            // Find all HandlerMappings in the ApplicationContext, including ancestor contexts.
            Map<String, HandlerMapping> matchingBeans =
                    BeanFactoryUtils.beansOfTypeIncludingAncestors(context, HandlerMapping.class, true, false);
            if (!matchingBeans.isEmpty()) {
                this.handlerMappings = new ArrayList<HandlerMapping>(matchingBeans.values());
                // We keep HandlerMappings in sorted order.
                OrderComparator.sort(this.handlerMappings);
            }
        }
        else {
            try {
                HandlerMapping hm = context.getBean(HANDLER_MAPPING_BEAN_NAME, HandlerMapping.class);
                this.handlerMappings = Collections.singletonList(hm);
            }
            catch (NoSuchBeanDefinitionException ex) {
                // Ignore, we'll add a default HandlerMapping later.
            }
        }

        //最后,确保有一个HandlerMapping,如果上面都找不到,就拿默认的
        // Ensure we have at least one HandlerMapping, by registering
        // a default HandlerMapping if no other mappings are found.
        if (this.handlerMappings == null) {
            this.handlerMappings = getDefaultStrategies(context, HandlerMapping.class);
            if (logger.isDebugEnabled()) {
                logger.debug("No HandlerMappings found in servlet '" + getServletName() + "': using default");
            }
        }
    }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值