當(dāng)web.xml文件中沒有配置contextClass這個(gè)參數(shù)時(shí),ServletContext是如何創(chuàng)建application容器的?
protected?Class<?>?determineContextClass(ServletContext?servletContext)?{ ???String?contextClassName?=?servletContext.getInitParameter(CONTEXT_CLASS_PARAM); ???if?(contextClassName?!=?null)?{ ??????try?{ ?????????return?ClassUtils.forName(contextClassName,?ClassUtils.getDefaultClassLoader()); ??????} ??????catch?(ClassNotFoundException?ex)?{ ?????????throw?new?ApplicationContextException( ???????????????"Failed?to?load?custom?context?class?["?+?contextClassName?+?"]",?ex); ??????} ???} ???else?{ ??????contextClassName?=?defaultStrategies.getProperty(WebApplicationContext.class.getName()); ??????try?{ ?????????return?ClassUtils.forName(contextClassName,?ContextLoader.class.getClassLoader()); ??????} ??????catch?(ClassNotFoundException?ex)?{ ?????????throw?new?ApplicationContextException( ???????????????"Failed?to?load?default?context?class?["?+?contextClassName?+?"]",?ex); ??????} ???} }
注:CONTEXT_CLASS_PARAM的值是contextClass,這個(gè)參數(shù)在web.xml中可以不配置。
2022-06-02
1)web.xml中沒有配置CONTEXT_CLASS_PARAM參數(shù),所有這塊邏輯是走
contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());這塊分支。而這句代碼目的是要構(gòu)建 【org.springframework.web.context.support.XmlWebApplicationContext】作為 WebApplicationContext 的實(shí)現(xiàn)類。具體配置開源可以看defaultStrategies的實(shí)例化賦值代碼。
2)后面的內(nèi)容就過度到XmlWebApplicationContext的創(chuàng)建過程,這必然涉及到如果獲取xml的配置路徑。
2.1 抽象模板類 AbstractRefreshableConfigApplicationContext::getConfigLocations方法中,有這樣的描述 (this.configLocations != null ? this.configLocations : getDefaultConfigLocations());
2.2 那重點(diǎn)就是 this.configLocations 的set 過程。
? ? 在ContextLoader::configureAndRefreshWebApplicationContext的方法中,我們可以找到這樣的代碼
wac.setConfigLocation(configLocationParam); 最終從 String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM); 這句代碼可以得知它的路徑來源是 web.xml中的配置
<param-name>contextConfigLocation</param-name>。
大體這樣的邏輯,希望可以幫到你。
2019-12-01
...