java?Spring的啟動原理詳解
引入
為什么突然說一下Spring啟動原理呢,因為之前面試的時候,回答的那可謂是坑坑洼洼,前前后后,補(bǔ)補(bǔ)貼貼。。。
總而言之就是不行,再次看一下源碼發(fā)掘一下。。。
在Spring Boot還沒有廣泛到家家在用的時候,我們都還在書寫繁瑣的配置,什么web.xml、spring.xml、bean.xml等等。雖然現(xiàn)在很少,可以說幾乎沒有企業(yè)在去使用Spring的老一套,而會去使用Spring Boot約定大于配置來進(jìn)行快速開發(fā),但是,Spring的也要去學(xué)習(xí),去挖掘,畢竟是我們Java程序員的基礎(chǔ)呀。
spring的啟動是建筑在servlet容器之上的,所有web工程的初始位置就是web.xml,它配置了servlet的上下文(context)和監(jiān)聽器(Listener)
web.xml
<!--上下文監(jiān)聽器,用于監(jiān)聽servlet的啟動過程--> <listener> <description>ServletContextListener</description> <!--這里是自定義監(jiān)聽器,個性化定制項目啟動提示--> <listener-class>com.trace.app.framework.listeners.ApplicationListener</listener-class> </listener> <!--dispatcherServlet的配置,這個servlet主要用于前端控制,這是springMVC的基礎(chǔ)--> <servlet> <servlet-name>service_dispatcher</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/services/service_dispatcher-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!--spring資源上下文定義,在指定地址找到spring的xml配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/application_context.xml</param-value> </context-param> <!--spring的上下文監(jiān)聽器--> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> <!--Session監(jiān)聽器,Session作為公共資源存在上下文資源當(dāng)中,這里也是自定義監(jiān)聽器--> <listener> <listener-class> com.trace.app.framework.listeners.MySessionListener </listener-class> </listener>
Spring啟動過程
spring的上下文監(jiān)聽器
<context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/application_context.xml</param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener>
spring的啟動其實就是IOC容器的啟動過程,通過上述的第一段配置 <context-param>
是初始化上下文,然后通過后一段的的<listener>
來加載配置文件,其中調(diào)用的spring包中的ContextLoaderListener
這個上下文監(jiān)聽器,ContextLoaderListener
是一個實現(xiàn)了ServletContextListener接口的監(jiān)聽器,他的父類是 ContextLoader,在啟動項目時會觸發(fā)contextInitialized上下文初始化方法。
public void contextInitialized(ServletContextEvent event) { initWebApplicationContext(event.getServletContext()); }
調(diào)用了父類ContextLoader的initWebApplicationContext(event.getServletContext());方法,很顯然,這是對ApplicationContext的初始化方法,也就是到這里正是進(jìn)入了springIOC的初始化。
接下來看一下initWebApplicationContext(event.getServletContext())的工作:
if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { throw new IllegalStateException( "Cannot initialize context because there is already a root application context present - " + "check whether you have multiple ContextLoader* definitions in your web.xml!"); } Log logger = LogFactory.getLog(ContextLoader.class); servletContext.log("Initializing Spring root WebApplicationContext"); if (logger.isInfoEnabled()) { logger.info("Root WebApplicationContext: initialization started"); } long startTime = System.currentTimeMillis(); try { // Store context in local instance variable, to guarantee that // it is available on ServletContext shutdown. if (this.context == null) { this.context = createWebApplicationContext(servletContext); } if (this.context instanceof ConfigurableWebApplicationContext) { ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; if (!cwac.isActive()) { // The context has not yet been refreshed -> provide services such as // setting the parent context, setting the application context id, etc if (cwac.getParent() == null) { // The context instance was injected without an explicit parent -> // determine parent for root web application context, if any. ApplicationContext parent = loadParentContext(servletContext); cwac.setParent(parent); } configureAndRefreshWebApplicationContext(cwac, servletContext); } } servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); ClassLoader ccl = Thread.currentThread().getContextClassLoader(); if (ccl == ContextLoader.class.getClassLoader()) { currentContext = this.context; } else if (ccl != null) { currentContextPerThread.put(ccl, this.context); } if (logger.isDebugEnabled()) { logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); } if (logger.isInfoEnabled()) { long elapsedTime = System.currentTimeMillis() - startTime; logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); } return this.context; } catch (RuntimeException ex) { logger.error("Context initialization failed", ex); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); throw ex; } catch (Error err) { logger.error("Context initialization failed", err); servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); throw err; }
總結(jié):
創(chuàng)建WebApplicationContext。加載對應(yīng)的spring配置文件中的Bean。將WebApplicationContext放入ServletContext(Java Web的全局變量)中。
接下來,來到了configureAndRefreshWebApplicationContext()
方法
作用:
就是用來加載spring配置文件中的Bean實例的。這個方法于封裝ApplicationContext數(shù)據(jù)并且初始化所有相關(guān)Bean對象。它會從web.xml
中讀取名為 contextConfigLocation的配置,這就是spring xml數(shù)據(jù)源設(shè)置,然后放到ApplicationContext中,最后調(diào)用傳說中的refresh
方法執(zhí)行所有Java對象的創(chuàng)建。
總結(jié):
總結(jié)
首先對于一個web應(yīng)用,需要部署到web容器中,web容器提供了一個全局的上下文環(huán)境,ServletContext,SpringIOC的宿主環(huán)境。
其次,在web容器啟動時,觸發(fā)容器初始化,web.xml中提供的有ContextLoaderListener監(jiān)聽器會監(jiān)聽這個事件,初始化方法contextInitialized被調(diào)用,初始化spring上下文
WebApplicationContext接口,實現(xiàn)類時XmlWebApplicationContext即SpringIOC容器,對應(yīng)的Bean定義是有context-param標(biāo)簽定義指定,然后存儲到ServletContext中,方便獲取。
ContextLoaderListener監(jiān)聽初始化完成后,開始初始化web.xml中配置的Servlet,指DisapatchServlet前端控制器,用來匹配,轉(zhuǎn)發(fā),處理每個Servlet請求,DisaptchServlet初始化時會創(chuàng)建自己的IOC上下文,用來持有Spring MVC的相關(guān)bean。
首先會從之前初始化存儲在ServletContext中的上下文左右parent上下文,再初始化自己的上下文,大概的工作就是初始化處理器映射、視圖解析等。這個servlet自己持有的上下文默認(rèn)實現(xiàn)類也是xmlWebApplicationContext。然后存儲到ServletContext。每個Servlet擁有自己的上下文,也會共享parent的上下文。
到此這篇關(guān)于java Spring的啟動原理詳解的文章就介紹到這了,更多相關(guān)java Spring啟動原理內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Spring @Bean注解的使用場景與案例實現(xiàn)
隨著SpringBoot的流行,我們現(xiàn)在更多采用基于注解式的配置從而替換掉了基于XML的配置,所以本篇文章我們主要探討基于注解的@Bean以及和其他注解的使用2023-03-03Kotlin 內(nèi)聯(lián)函數(shù)詳解及實例
這篇文章主要介紹了Kotlin 內(nèi)聯(lián)函數(shù)詳解及實例的相關(guān)資料,需要的朋友可以參考下2017-06-06Java數(shù)據(jù)結(jié)構(gòu)之鏈表的概念及結(jié)構(gòu)
這篇文章主要介紹了數(shù)據(jù)鏈表的概念及結(jié)構(gòu),鏈表是一種物理存儲結(jié)構(gòu)上非連續(xù)、非順序的存儲結(jié)構(gòu),數(shù)據(jù)元素的邏輯順序是通過鏈表中的指針鏈接次序?qū)崿F(xiàn)的。想進(jìn)一步了解的同學(xué),可以參考閱讀本文2023-04-04Java中雙重檢查鎖(double checked locking)的正確實現(xiàn)
雙重檢查鎖(Double-Check Locking),顧名思義,通過兩次檢查,并基于加鎖機(jī)制,實現(xiàn)某個功能,下面這篇文章主要給大家介紹了關(guān)于Java中雙重檢查鎖(double checked locking)的相關(guān)資料,需要的朋友可以參考下2021-09-09詳解Spring MVC的異步模式(高性能的關(guān)鍵)
本篇文章主要介紹了詳解Spring MVC的異步模式(高性能的關(guān)鍵),小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-02-02