SpringMVC啓動分析

如下分析基於JDK1.8web

dfd2c59af095fb78a6826fce19fc46bb.png

啓動的第一步是執行監聽器,這裏web.xml中配置了一個監聽器org.springframework.web.context.ContextLoaderListener
spring

接下來,看ContextLoaderLisener
app

e75b9a2945fdbe5ab5ae239c29903141.png

5b53527236ad1bd5a56c2de6cfc6af8e.png

604e0485caf63f4a31551cd5d58601af.png

285d82d176116a5ebd4290ae56aa1752.png

在Web應用啓動的時候,全部的ServletContextListener會在filter和servlet以前執行,因此這裏會首先執行contextInitialized方法
ide

6308613ac89a92caa6794dfbf4cf76c2.png


2e13472ae07957f840687cf7cadf52e0.png


接下來,看一下XmlWebApplicationContext在實例化的時候作了什麼spa

答案是並無,就是實例化一個對象3d

接下來,isActive確定是false的xml

因而乎,配置XmlWebApplicationContext對象

dc8ddc130acede1bc312c4308ad1222a.png

在這段代碼中最重要的是wac.refresh()
blog

refresh()方法前面的文章中已經看過了,這裏再也不看了。在這個方法中很重要的一個步驟是獲取BeanFactory以前會加載全部的BeanDefinition,而XmlWebApplicationContext中就定義瞭如何加載這些Bean定義繼承

c5ffb1323e5e5e1a05c6dd054ed44171.png

a4a8300c46b2ec82e1e306ef19465b21.png

至此,WebApplicationContext已經建立好了,最後將其設置到ServletContext中



到這裏,只完成了監聽器的工做,接下來是Servlet

4de7a82ee51cf26acaeb9cdf45ac5b38.png

做爲標準的Servlet,DispatcherServlet的init()方法是繼承HttpServletBean的,而HttpServletBean在其init()方法中最重要的一件事是調用initServletBean()方法,而initServletBean()在HttpServletBean中是一個抽象方法,具體是在FrameworkServlet中實現的。下面具體看下FrameworkServlet

fa732f7e514fdb1c1bb2747459e2b56b.png

initServletBean中作了兩件事情,一個是建立WebApplicationContext,另外一個是初始化SpringMvc的一些組件

下面,重點看這兩個方法

14833d48c31ad690292b7d792bd0a18f.png


6d49118d83300593c5bdd6cfe2be83f3.png這裏有一點須要注意,在本示例中,咱們在web.xml中配置DispatcherServlet的時候並無指定<init-param>全部,在這一步中getContextConfigLocation()是null

9d0569fb60d4ab1f062226b3563168df.png


又看到調用refresh()方法了,這個方法中重要的一步是加載BeanDefinition。

那麼,它從哪兒去加載呢?固然是配置文件啦。

那麼,它是怎麼找到配置文件的呢?看XmlWebApplicationContext中是如何加載Bean定義的。

3674bd26fd47236c05aee7fa57c07b57.png

ee02b1429904de9d06fb82167474a601.png

至此,SpringMVC的WebApplicationContext也建立好了。

先來總結一下,這一步其實就是基於以前Spring的WebApplicationContext再建立一個SpringMVC本身的WebApplicationContext,兩者構成父子關係,由於在建立後置的時候setParent()了。

建立第一個WebApplicationContext的時候依據的是Spring的配置文件applicationContext.xml

建立第二個WebApplicationContext的時候依據的是SpringMVC的配置文件xxx-servlet.xml



最後一步,調用FrameworkServlet的onRefresh()方法,這個方法是在其子類DispatcherServlet中實現的。這一步所作的工做就是將在xxx-servlet.xml中配置的各類組件注入到DispatcherServlet中對應的成員變量中。而這些組件在上一步建立WebApplicationContext的時候已經被容器管理起來了,因此,直接從容器中獲取便可。

若是配置文件中沒有配置的話,會根據一些策略進行默認的自動配置。

141188309c12934b16be856436e85d63.png

23723dfae20b5eaa48b64337bd95b818.png


30eda0e69d1501733fce047b565c4a9c.png

至此,SpringMVC就啓動成功了。

整個SpringMVC啓動的過程就是建立兩個父子WebApplicationContext的過程

下面總一下啓動過程:

(1)建立Spring的WebApplicationContext,並將其放到ServletContext中

(2)根據ServletContext中的WebApplicationContext建立SpringMVC的WebApplicationContext

(3)從上一步中的WebApplicationContext中獲取Bean而且設置到DispatcherServlet中


再簡練一點就是,

(1)實例化applicationContext.xml中定義的Bean

(2)實例化xxx-servlet.xml中定義的Bean

(3)將SpringMVC本身特有的Bean設置到DispatcherServlet中

其實,後兩步能夠歸結爲實例化DispatcherServlet

相關文章
相關標籤/搜索