spring启动加载流程
上次看了spring的加載流程,今天發(fā)現(xiàn)或多都忘記了,今天又看了一下,順便總結(jié)一下:
標題spring的web項目啟動:
1、首先web容器(比如Tomcat)會讀取配置在web.xml中的監(jiān)聽器,從而啟動spring容器。
<!--web項目中上下文初始化參數(shù), name value的形式 --> <context-param><param-name>contextConfigLocation</param-name><param-value>/WEB-INF/applicationContext.xml</param-value> </context-param><!--ContextLoaderListener,會通過它的監(jiān)聽啟動spring容器--> <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener><!--DispatherServlet,前端MVC核心,分發(fā)器,SpringMVC的核心--> <servlet><servlet-name>dispatcher</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup> </servlet>1、web容器(如tomcat)讀取web.xml, 創(chuàng)建ServletContext,它是web的上下文,整個web項目都會用到它。
2、讀取context-param節(jié)點,它以 鍵值對的形式出現(xiàn)。將節(jié)點值轉(zhuǎn)化為鍵值對,傳給ServletContext。(默認的文件為/WEB-INF/applicationContext.xml)。
3、容器創(chuàng)建中的實例,創(chuàng)建監(jiān)聽器。監(jiān)聽器必須繼承ServletContextListener 調(diào)用ServletContextListener的contextInitialized()方法,spring容器的創(chuàng)建和初始化就是在這個方法中。
4、在web容器初始化過程中,會創(chuàng)建節(jié)點的監(jiān)聽器,并調(diào)用它的contextInitialized()方法。這個方法中會完成spring容器的創(chuàng)建,初始化,以及beans的創(chuàng)建。(會調(diào)用以下方法)
initWebApplicationContext()主要做三件事
- 創(chuàng)建WebApplicationContext,通過createWebApplicationContext()方法
加載spring配置文件,并創(chuàng)建beans。 - 通過configureAndRefreshWebApplicationContext()方法
- 將spring容器context掛載到ServletContext
- 這個web容器上下文中。通過servletContext.setAttribute()方法。
createWebApplicationContext 創(chuàng)建spring容器 - 獲取WebApplicationContext實現(xiàn)類的class對象
- 根據(jù)class對象創(chuàng)建實例對象
configureAndRefreshWebApplicationContext加載spring配置文件,創(chuàng)建beans
configureAndRefreshWebApplicationContext()這個方法會先讀取web.xml中聲明的contextConfigLocation元素,通過它找到spring配置文件。然后在refresh()方法中讀取配置文件,并創(chuàng)建和初始化beans。所以重中之重還是refresh()方法
流程圖
spring容器初始化的整個流程圖如下
創(chuàng)建WebApplicationContext對象流程如下
讀取XML配置文件,創(chuàng)建beans流程如下
轉(zhuǎn)載:https://blog.csdn.net/u013510838/article/details/75066884
注:web.xml的加載順序是:context-param-listener-filter-servlet。其中,如果web.xml中出現(xiàn)了相同的元素,則按照在配置文件中出現(xiàn)的先后順序來加載。
總結(jié)
以上是生活随笔為你收集整理的spring启动加载流程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: session监听器统计在线人数存入数值
- 下一篇: idea没法识别java文件,idea文