原創作品,可以轉載,但是請標注出處地址:https://www.cnblogs.com/V1haoge/p/9502069.html
一、概述
我說的容器啟動流程涉及兩種情況,SSM開發模式和Springboot開發模式。
SSM開發模式中,需要配置web.xml文件用作啟動配置文件,而Springboot開發模式中由main方法直接啟動。
下面是web項目中容器啟動的流程,起點是web.xml中配置的ContextLoaderListener監聽器。
二、調用流程圖(右鍵可查看大圖)
三、流程解析
Tomcat服務器啟動時會讀取項目中web.xml中的配置項來生成ServletContext,在其中注冊的ContextLoaderListener是ServletContextListener接口的實現類,它會時刻監聽ServletContext的動作,包括創建和銷毀,ServletContext創建的時候會觸發其contextInitialized()初始化方法的執行。而Spring容器的初始化操作就在這個方法之中被觸發。
源碼1-來自:ContextLoaderListener
1 /** 2 * Initialize the root web application context. 3 */ 4 @Override 5 public void contextInitialized(ServletContextEvent event) { 6 initWebApplicationContext(event.getServletContext()); 7 }
ContextLoaderListener是啟動和銷毀Spring的根WebApplicationContext(web容器或者web應用上下文)的引導器,其中實現了ServletContextListener的contextInitialized容器初始化方法與contextDestoryed銷毀方法,用於引導根web容器的創建和銷毀。
上面方法中contextInitialized就是初始化根web容器的方法。其中調用了initWebApplicationContext方法進行Spring web容器的具體創建。
源碼2-來自:ContextLoader
1 public WebApplicationContext initWebApplicationContext(ServletContext servletContext) { 2 //SpringIOC容器的重復性創建校驗 3 if (servletContext.getAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE) != null) { 4 throw new IllegalStateException( 5 "Cannot initialize context because there is already a root application context present - " + 6 "check whether you have multiple ContextLoader* definitions in your web.xml!"); 7 } 8 9 Log logger = LogFactory.getLog(ContextLoader.class); 10 servletContext.log("Initializing Spring root WebApplicationContext"); 11 if (logger.isInfoEnabled()) { 12 logger.info("Root WebApplicationContext: initialization started"); 13 } 14 //記錄Spring容器創建開始時間 15 long startTime = System.currentTimeMillis(); 16 17 try { 18 // Store context in local instance variable, to guarantee that 19 // it is available on ServletContext shutdown. 20 if (this.context == null) { 21 //創建Spring容器實例 22 this.context = createWebApplicationContext(servletContext); 23 } 24 if (this.context instanceof ConfigurableWebApplicationContext) { 25 ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context; 26 if (!cwac.isActive()) { 27 //容器只有被刷新至少一次之后才是處於active(激活)狀態 28 if (cwac.getParent() == null) { 29 //此處是一個空方法,返回null,也就是不設置父級容器 30 ApplicationContext parent = loadParentContext(servletContext); 31 cwac.setParent(parent); 32 } 33 //重點操作:配置並刷新容器 34 configureAndRefreshWebApplicationContext(cwac, servletContext); 35 } 36 } 37 //將創建完整的Spring容器作為一條屬性添加到Servlet容器中 38 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context); 39 40 ClassLoader ccl = Thread.currentThread().getContextClassLoader(); 41 if (ccl == ContextLoader.class.getClassLoader()) { 42 //如果當前線程的類加載器是ContextLoader類的類加載器的話,也就是說如果是當前線程加載了ContextLoader類的話,則將Spring容器在ContextLoader實例中保留一份引用 43 currentContext = this.context; 44 } 45 else if (ccl != null) { 46 //添加一條ClassLoader到Springweb容器的映射 47 currentContextPerThread.put(ccl, this.context); 48 } 49 50 if (logger.isDebugEnabled()) { 51 logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" + 52 WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]"); 53 } 54 if (logger.isInfoEnabled()) { 55 long elapsedTime = System.currentTimeMillis() - startTime; 56 logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms"); 57 } 58 59 return this.context; 60 } 61 catch (RuntimeException ex) { 62 logger.error("Context initialization failed", ex); 63 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex); 64 throw ex; 65 } 66 catch (Error err) { 67 logger.error("Context initialization failed", err); 68 servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err); 69 throw err; 70 } 71 }
這里十分明了的顯示出了ServletContext和Spring root ApplicationContext的關系:后者只是前者的一個屬性,前者包含后者。
ServletContext表示的是一整個應用,其中囊括應用的所有內容,而Spring只是應用所采用的一種框架。從ServletContext的角度來看,Spring其實也算是應用的一部分,屬於和我們編寫的代碼同級的存在,只是相對於我們編碼人員來說,Spring是作為一種即存的編碼架構而存在的,即我們將其看作我們編碼的基礎,或者看作應用的基礎部件。雖然是基礎部件,但也是屬於應用的一部分。所以將其設置到ServletContext中,而且是作為一個單一屬性而存在,但是它的作用卻是很大的。
源碼中WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE的值為:WebApplicationContext.class.getName() + ".ROOT",這個正是Spring容器在Servlet容器中的屬性名。
在這段源碼中主要是概述Spring容器的創建和初始化,分別由兩個方法實現:createWebApplicationContext方法和configureAndRefreshWebApplicationContext方法。
首先,我們需要創建Spring容器,我們需要決定使用哪個容器實現。
源碼3-來自:ContextLoader
1 protected WebApplicationContext createWebApplicationContext(ServletContext sc) { 2 //決定使用哪個容器實現 3 Class<?> contextClass = determineContextClass(sc); 4 if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) { 5 throw new ApplicationContextException("Custom context class [" + contextClass.getName() + 6 "] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]"); 7 } 8 //反射方式創建容器實例 9 return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass); 10 }
1 //我們在web.xml中以 <context-param> 的形式設置contextclass參數來指定使用哪個容器實現類, 2 //若未指定則使用默認的XmlWebApplicationContext,其實這個默認的容器實現也是預先配置在一個 3 //叫ContextLoader.properties文件中的 4 protected Class<?> determineContextClass(ServletContext servletContext) { 5 //獲取Servlet容器中配置的系統參數contextClass的值,如果未設置則為null 6 String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM); 7 if (contextClassName != null) { 8 try { 9 return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader()); 10 } 11 catch (ClassNotFoundException ex) { 12 throw new ApplicationContextException( 13 "Failed to load custom context class [" + contextClassName + "]", ex); 14 } 15 } 16 else { 17 //獲取預先配置的容器實現類 18 contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName()); 19 try { 20 return ClassUtils.forName(contextClassName, ContextLoader.class.getClassLoader()); 21 } 22 catch (ClassNotFoundException ex) { 23 throw new ApplicationContextException( 24 "Failed to load default context class [" + contextClassName + "]", ex); 25 } 26 } 27 }
BeanUtils是Spring封裝的反射實現,instantiateClass方法用於實例化指定類。
我們可以在web.xml中以 <context-param> 的形式設置contextclass參數手動決定應用使用哪種Spring容器,但是一般情況下我們都遵循Spring的默認約定,使用ContextLoader.properties中配置的org.springframework.web.context.WebApplicationContext的值來作為默認的Spring容器來創建。
源碼4-來自:ContextLoader.properties
1 # Default WebApplicationContext implementation class for ContextLoader. 2 # Used as fallback when no explicit context implementation has been specified as context-param. 3 # Not meant to be customized by application developers. 4 5 org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
可見,一般基於Spring的web服務默認使用的都是XmlWebApplicationContext作為容器實現類的。
到此位置容器實例就創建好了,下一步就是配置和刷新了。
源碼4-來自:ContextLoader
1 protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) { 2 if (ObjectUtils.identityToString(wac).equals(wac.getId())) { 3 // The application context id is still set to its original default value 4 // -> assign a more useful id based on available information 5 String idParam = sc.getInitParameter(CONTEXT_ID_PARAM); 6 if (idParam != null) { 7 wac.setId(idParam); 8 } 9 else { 10 // Generate default id... 11 wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX + 12 ObjectUtils.getDisplayString(sc.getContextPath())); 13 } 14 } 15 //在當前Spring容器中保留對Servlet容器的引用 16 wac.setServletContext(sc); 17 //設置web.xml中配置的contextConfigLocation參數值到當前容器中 18 String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); 19 if (configLocationParam != null) { 20 wac.setConfigLocation(configLocationParam); 21 } 22 23 // The wac environment's #initPropertySources will be called in any case when the context 24 // is refreshed; do it eagerly here to ensure servlet property sources are in place for 25 // use in any post-processing or initialization that occurs below prior to #refresh 26 //在容器刷新之前,提前進行屬性資源的初始化,以備使用,將ServletContext設置為servletContextInitParams 27 ConfigurableEnvironment env = wac.getEnvironment(); 28 if (env instanceof ConfigurableWebEnvironment) { 29 ((ConfigurableWebEnvironment) env).initPropertySources(sc, null); 30 } 31 //取得web.xml中配置的contextInitializerClasses和globalInitializerClasses對應的初始化器,並執行初始化操作,需自定義初始化器 32 customizeContext(sc, wac); 33 //刷新容器 34 wac.refresh(); 35 }
首先將ServletContext的引用置入Spring容器中,以便可以方便的訪問ServletContext;然后從ServletContext中找到“contextConfigLocation”參數的值,配置是在web.xml中以<context-param>形式配置的。
在Spring中凡是以<context-param>配置的內容都會在web.xml加載的時候優先存儲到ServletContext之中,我們可以將其看成ServletContext的配置參數,將參數配置到ServletContext中后,我們就能方便的獲取使用了,就如此處我們就能直接從ServletContext中獲取“contextConfigLocation”的值,用於初始化Spring容器。
在Java的web開發中,尤其是使用Spring開發的情況下,基本就是一個容器對應一套配置,這套配置就是用於初始化容器的。ServletContext對應於<context-param>配置,Spring容器對應applicationContext.xml配置,這個配置屬於默認的配置,如果自定義名稱就需要將其配置到<context-param>中備用了,還有DispatchServlet的Spring容器對應spring-mvc.xml配置文件。
Spring容器的environment表示的是容器運行的基礎環境配置,其中保存的是Profile和Properties,其initPropertySources方法是在ConfigurableWebEnvironment接口中定義的,是專門用於web應用中來執行真實屬性資源與占位符資源(StubPropertySource)的替換操作的。
StubPropertySource就是一個占位用的實例,在應用上下文創建時,當實際屬性資源無法及時初始化時,臨時使用這個實例進行占位,等到容器刷新的時候執行替換操作。
上面源碼中customizeContext方法的目的是在刷新容器之前對容器進行自定義的初始化操作,需要我們實現ApplicationContextInitializer<C extends ConfigurableApplicationContext>接口,然后將其配置到web.xml中即可生效。
源碼5-來自:ContextLoader
1 protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) { 2 //獲取初始化器類集合 3 List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses = 4 determineContextInitializerClasses(sc); 5 6 for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) { 7 Class<?> initializerContextClass = 8 GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class); 9 if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) { 10 throw new ApplicationContextException(String.format( 11 "Could not apply context initializer [%s] since its generic parameter [%s] " + 12 "is not assignable from the type of application context used by this " + 13 "context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(), 14 wac.getClass().getName())); 15 } 16 //實例化初始化器並添加到集合中 17 this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass)); 18 } 19 //排序並執行,編號越小越早執行 20 AnnotationAwareOrderComparator.sort(this.contextInitializers); 21 for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) { 22 initializer.initialize(wac); 23 } 24 }
1 protected List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> 2 determineContextInitializerClasses(ServletContext servletContext) { 3 4 List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> classes = 5 new ArrayList<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>>(); 6 //通過<context-param>屬性配置globalInitializerClasses獲取全局初始化類名 7 String globalClassNames = servletContext.getInitParameter(GLOBAL_INITIALIZER_CLASSES_PARAM); 8 if (globalClassNames != null) { 9 for (String className : StringUtils.tokenizeToStringArray(globalClassNames, INIT_PARAM_DELIMITERS)) { 10 classes.add(loadInitializerClass(className)); 11 } 12 } 13 //通過<context-param>屬性配置contextInitializerClasses獲取容器初始化類名 14 String localClassNames = servletContext.getInitParameter(CONTEXT_INITIALIZER_CLASSES_PARAM); 15 if (localClassNames != null) { 16 for (String className : StringUtils.tokenizeToStringArray(localClassNames, INIT_PARAM_DELIMITERS)) { 17 classes.add(loadInitializerClass(className)); 18 } 19 } 20 21 return classes; 22 }
initPropertySources操作用於配置屬性資源,其實在refresh操作中也會執行該操作,這里提前執行,目的為何,暫未可知。
到達refresh操作我們先暫停。refresh操作是容器初始化的操作。是通用操作,而到達該點的方式確實有多種,每種就是一種Spring的開發方式。
除了此處的web開發方式,還有Springboot開發方式,貌似就兩種。。。下面說說Springboot啟動的流程,最后統一說refresh流程。