基于springmvc的web應用在初始化時做了什么?application context何時加載?有幾種加載方式?
?
和所有的java web框架一樣,springmvc實際上就是在典型的servlet處理request的流程上再包裹了一層而已。springmvc的初始化流程也同樣和容器初始化servlet流程一樣。容器初始化servlet上下文的流程如下,servlet context一般而言就是那個web.xml里設定上下文環境。
?
springmvc中最典型的ServletContextListener實現就是ContextLoaderListener,其重寫的contextInitialized方法
定義了spring在初始化servletContext時的一些動作。
其會加載由context-param參數contextConfigLocation中指定的spring application context配置文件。
配置如下:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml /WEB-INF/applicationContext2.xml
</param-value>
</context-param>
?
使用 contextConfigLocation 加載指定路徑的配置文件時,多個配置文件可以用
逗號,冒號,空格, \t,\n
中任一個來分隔。
如果沒有指定contextConfigLocation 參數,ContextLoaderListener會默認加載/WEB-INF/applicationContext.xml這個配置文件。
springmvc將由ContextLoaderListener 載入的application context 叫做
"root application context"
,以區別于servlet的application context。
ServletContextListener在servlet context里的配置參考如下:
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
?
如果沒有在servlet context里配置,就不存在"root application context"。
springmvc可以配置多個servlet,每一個 servlet都擁有各自的application context,相互之間不能相互訪問。但是"root application context"卻是對所有servlet都是可見的。
如果servlet直接使用DispatcherServlet,其application context在DispatcherServlet的
init
方法被調用時初始化。
servlet application context的加載策略類似于root application context,首先會查找是否配置了servlet的init-param "contextConfigLocation",如果有,就使用 contextConfigLocation 指定的路徑加載的配置文件時,多個配置文件可以用
逗號,冒號,空格, \t,\n
中任一個來分隔。
如果沒有指定"contextConfigLocation"參數,則會在?? /WEB-INF/下查找
"servlet-name"+"-servlet.xml"
這樣的文件加載。如下配置所示,就是
/WEB-INF/springDispatcherServlet-servlet.xml
。
<servlet>
<servlet-name>springDispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/servlet-applicationContext.xml
</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springDispatcherServlet</servlet-name>
<url-pattern>/mvc/*</url-pattern>
</servlet-mapping>
?
最后,該servlet application context將root application context設置為parent,然后加載完成。
以后在應用里調用applicationContext或者beanFactory的getBean方法去獲取實例的時候,都是先嘗試從父級application context獲取,獲取不到,再到當前application context里獲取。
除此之外,我們還可以在某個類里以編程式加載application context,比如使用ClassPathXmlApplicationContext或FileSystemXmlApplicationContext。不過這樣加載的application context和root application context和servlet application context 分屬于不同的可見范圍。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

