springbank 开发日志 阅读spring mvc的源代码真是受益良多

决定模仿spring mvc的dispatcher->handlerMapping(return executorChain)->handler.execute 这样的流程之后,就开始看spring mvc的源代码。

因为我也自定义了标签,来做交易名映射,根据交易名找到处理类。所以我着重需要看的,就是spring mvc是如何根据url找到对应的handler的。

既然要找,首先要有个找的地方,spring mvc是这样做的,它搞了AbstractDetectingUrlHandlerMapping类,这个类的继承体系如下,其中ApplicationObjectSupport这个抽象父类是实现了ApplicationContextAware的,也就是说Spring一旦启动完成,就会去调用它的setApplicationContext方法,然后这里面又搞了一个抽象的initApplicationContext()方法,

AbstractDetectingUrlHandlerMapping实现了initApplicationContext这个方法:

  @Override
    public void initApplicationContext() throws ApplicationContextException {
        super.initApplicationContext();
        detectHandlers();
    }

然后这里的determineUrlsForHandler(String beanName);又是一个抽象方法,这个方法在下面这张图最下面的两个子类中得到了实现。

实际上取得了怎样的效果呢?效果就是BeanNameUrlHandlerMapping和DefaultAnnotationHandlerMapping这两个类都间接继承了initApplicationContext方法,并且都会调用各自的detectHandlers()去查找注册handler,真是很好的设计,感叹啊

看了半天的源代码,让我总结一下,到底springmvc是怎么注册handler的,所谓的注册, 就是在一个将(ulr,beanName)放入一个map中

1.如上所说,走到DefaultAnnotationHandlerMapping的detectHandlers方法

2.在上面这个方法里面,String[] urls = determineUrlsForHandler(beanName);通过beanName找到例如/helloworld这样的urls,

3.regist

原文地址:https://www.cnblogs.com/heben/p/7154718.html