DispatcherServlet初始化源码分析
DispatcherServlet是SpringMVC的核心分发器,它实现了请求分发,是处理请求的入口,本篇将深入源码分析它的初始化过程。
首先,从DispatcherServlet的名称上可以看出它是一个Servlet,通过一张图来看一下它的实现关系。

既然DispatcherServlet是一个Servlet,那么初始化的时候一定会执行init方法,查看源码发现DispatcherServlet的init方法继承自HttpServletBean,具体代码如下图所示。

对于上面的代码,配合一个实际的web.xml配置样例更容易理解,具体如下图所示。

上面示例配置中,配置了一个 contextConfigLocation参数,该参数用于构造SpringMVC上下文。对于initServletBean方法,FrameworkServlet中进行了重写,具体代码如下图所示。

initWebApplicationContext方法主要代码如下图所示。

如果web.xml中配置了如下参数,将会在应用启动的时候初始化一个WebApplicationContext实例,并将其保存在ServletContext中。

上图中的代码很容易理解,接下来进入DispatcherServlet的onRefresh方法,具体代码如下图所示。

initStrategies方法中的各个方法,从方法名上可以很容易理解其作用,大部分的执行逻辑都是先从WebApplicationContext中查找,找不到的情况下再加载和DispatcherServlet同目录下的DispatcherServlet.properties中的各个策略,如初始化HandlerMapping,具体如下图所示。

