1. Web應用上下文環(huán)境創(chuàng)建簡析
通過上一節(jié)的分析,找到了SpringMVC源碼分析的入口脉让,接下來看Web應用上下文環(huán)境創(chuàng)建過程桂敛。打開ContextLoader類的initWebApplicationContext方法:
public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
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!");
}
servletContext.log("Initializing Spring root WebApplicationContext");
Log logger = LogFactory.getLog(ContextLoader.class);
if (logger.isInfoEnabled()) {
logger.info("Root WebApplicationContext: initialization started");
}
long startTime = System.currentTimeMillis();
try {
// 將上下文存儲在本地實例變量中功炮,以確保它在ServletContext關(guān)閉時可用。
// Store context in local instance variable, to guarantee that it is available on ServletContext shutdown.
if (this.context == null) {
// 1.創(chuàng)建web應用上線文環(huán)境
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
// 如果當前上下文環(huán)境未激活术唬,那么其只能提供例如設置父上下文薪伏、設置上下文id等功能
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);
}
// 2.配置并刷新當前上下文環(huán)境
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
// 將當前上下文環(huán)境存儲到ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE變量中
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.isInfoEnabled()) {
long elapsedTime = System.currentTimeMillis() - startTime;
logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
}
return this.context;
}
catch (RuntimeException | Error ex) {
logger.error("Context initialization failed", ex);
servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
throw ex;
}
}
該方法一共涉及兩個比較重要的點:
- 創(chuàng)建web應用上線文環(huán)境
- 配置并刷新當前上下文環(huán)境
2. 創(chuàng)建web應用上線文環(huán)境
/**
* 為當前類加載器實例化根WebApplicationContext,可以是默認上線文加載類或者自定義上線文加載類
*/
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
// 1.確定實例化WebApplicationContext所需的類
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
// 2.實例化得到的WebApplicationContext類
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
邏輯很簡單,得到一個類粗仓,將其實例化嫁怀。我們經(jīng)常說的web應用上下文環(huán)境,是不是比我們想象的還要簡單借浊。塘淑。。
那么要得到或者明確哪個類呢巴碗? 繼續(xù)看代碼:
/**
* 返回WebApplicationContext(web應用上線文環(huán)境)實現(xiàn)類
* 如果沒有自定義默認返回XmlWebApplicationContext類
*
* 兩種方式:
* 1朴爬。非自定義:通過ContextLoader類的靜態(tài)代碼塊加載ContextLoader.properties配置文件并解析,該配置文件中的默認類即XmlWebApplicationContext
* 2橡淆。自定義: 通過在web.xml文件中召噩,配置context-param節(jié)點,并配置param-name為contextClass的自己點逸爵,如
* <context-param>
* <param-name>contextClass</param-name>
* <param-value>org.springframework.web.context.support.MyWebApplicationContext</param-value>
* </context-param>
*
* Return the WebApplicationContext implementation class to use, either the
* default XmlWebApplicationContext or a custom context class if specified.
* @param servletContext current servlet context
* @return the WebApplicationContext implementation class to use
* @see #CONTEXT_CLASS_PARAM
* @see org.springframework.web.context.support.XmlWebApplicationContext
*/
protected Class<?> determineContextClass(ServletContext servletContext) {
String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
// 1.自定義
if (contextClassName != null) {
try {
return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
}
catch (ClassNotFoundException ex) {
throw new ApplicationContextException("Failed to load custom context class [" + contextClassName + "]", ex);
}
}
// 2.默認
else {
// 根據(jù)靜態(tài)代碼塊的加載這里 contextClassName = XmlWebApplicationContext
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);
}
}
}
自定義方式注釋里已經(jīng)寫的很清晰了具滴,我們來看默認方式,這里涉及到了一個靜態(tài)變量defaultStrategies师倔,并在下面的靜態(tài)代碼塊中對其進行了初始化操作:
private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";
private static final Properties defaultStrategies;
/**
* 靜態(tài)代碼加載默認策略,即默認的web應用上下文
* DEFAULT_STRATEGIES_PATH --> ContextLoader.properties
*
* org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
*/
static {
// Load default strategy implementations from properties file.
// This is currently strictly internal and not meant to be customized by application developers.
try {
ClassPathResource resource = new ClassPathResource(DEFAULT_STRATEGIES_PATH, ContextLoader.class);
defaultStrategies = PropertiesLoaderUtils.loadProperties(resource);
}
catch (IOException ex) {
throw new IllegalStateException("Could not load 'ContextLoader.properties': " + ex.getMessage());
}
}
這段代碼對ContextLoader.properties進行了解析构韵,那么ContextLoader.properties中存儲的內(nèi)容是什么呢?
# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.
org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext
很簡單趋艘,通過上面的操作疲恢,我們就可以確定contextClassName是XmlWebApplicationContext,跟我們之前分析的ApplicationContext差不多瓷胧,只是在其基礎(chǔ)上又提供了對web的支持显拳。接下來通過BeanUtils.instantiateClass(contextClass)將其實例化即可。
3.配置并刷新當前上下文環(huán)境
/**
* 配置并刷新當前web應用上下文
*/
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
/**
* 1.配置應用程序上下文id
* 如果當前應用程序上下文id仍然設置為其原始默認值,則嘗試為其設置自定義上下文id搓萧,如果有的話杂数。
* 在web.xml中配置
* <context-param>
* <param-name>contextId</param-name>
* <param-value>jack-2019-01-02</param-value>
* </context-param>
*/
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
wac.setId(idParam);
}
// 無自定義id則為其生成默認id
else {
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
/**
* 2.設置配置文件路徑,如
* <context-param>
* <param-name>contextConfigLocation</param-name>
* <param-value>classpath:spring-context.xml</param-value>
* </context-param>
*/
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
// The wac environment's #initPropertySources will be called in any case when the context
// is refreshed; do it eagerly here to ensure servlet property sources are in place for
// use in any post-processing or initialization that occurs below prior to #refresh
// 3.創(chuàng)建ConfigurableEnvironment并配置初始化參數(shù)
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
// 4.自定義配置上下文環(huán)境
customizeContext(sc, wac);
// 5.刷新上下文環(huán)境
wac.refresh();
}
前三個步驟比較簡單瘸洛,在前面的博客中多少有些介紹揍移,我們來看自定義配置上下文環(huán)境和刷新上下文環(huán)境
3.1 自定義配置上下文環(huán)境
protected void customizeContext(ServletContext sc, ConfigurableWebApplicationContext wac) {
/**
* 加載并實例化web.xml配置文件中的 globalInitializerClasses 和 contextInitializerClasses 配置
*
* globalInitializerClasses 代表所有的web application都會應用
* contextInitializerClasses 代表只有當前的web application會使用
* 例如,在web.xml配置文件中:
* <context-param>
* <param-name>contextInitializerClasses</param-name>
* <param-value>com.lyc.cn.init.MyContextInitializerClasses</param-value>
* </context-param>
*
* 容器將會調(diào)用自定義的initialize方法反肋,其實就在這段代碼的下方那伐。。。
*/
List<Class<ApplicationContextInitializer<ConfigurableApplicationContext>>> initializerClasses =
determineContextInitializerClasses(sc);
for (Class<ApplicationContextInitializer<ConfigurableApplicationContext>> initializerClass : initializerClasses) {
Class<?> initializerContextClass =
GenericTypeResolver.resolveTypeArgument(initializerClass, ApplicationContextInitializer.class);
if (initializerContextClass != null && !initializerContextClass.isInstance(wac)) {
throw new ApplicationContextException(String.format(
"Could not apply context initializer [%s] since its generic parameter [%s] " +
"is not assignable from the type of application context used by this " +
"context loader: [%s]", initializerClass.getName(), initializerContextClass.getName(),
wac.getClass().getName()));
}
this.contextInitializers.add(BeanUtils.instantiateClass(initializerClass));
}
AnnotationAwareOrderComparator.sort(this.contextInitializers);
for (ApplicationContextInitializer<ConfigurableApplicationContext> initializer : this.contextInitializers) {
initializer.initialize(wac);
}
}
該實現(xiàn)很簡單喧锦,我們只要在web.xml中自定義contextInitializerClasses和globalInitializerClasses并提供實現(xiàn)類即可:
如:
<context-param>
<param-name>contextInitializerClasses</param-name>
<param-value>com.lyc.cn.init.MyContextInitializerClasses</param-value>
</context-param>
public class MyContextInitializerClasses implements ApplicationContextInitializer<XmlWebApplicationContext> {
/**
* Initialize the given application context.
* @param applicationContext the application to configure
*/
@Override
public void initialize(XmlWebApplicationContext applicationContext) {
System.out.println("MyContextInitializerClasses initialize ...");
System.out.println("MyContextInitializerClasses " + applicationContext.toString());
}
}
3.2 刷新上下文環(huán)境
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 1读规、準備刷新上下文環(huán)境
prepareRefresh();
// 2、讀取xml并初始化BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3燃少、填充BeanFactory功能
prepareBeanFactory(beanFactory);
try {
// 4、子類覆蓋方法額外處理(空方法)
postProcessBeanFactory(beanFactory);
// 5铃在、調(diào)用BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
// 6阵具、注冊BeanPostProcessors
registerBeanPostProcessors(beanFactory);
// 7、初始化Message資源
initMessageSource();
// 8定铜、初始事件廣播器
initApplicationEventMulticaster();
// 9阳液、留給子類初始化其他Bean(空的模板方法)
onRefresh();
// 10、注冊事件監(jiān)聽器
registerListeners();
// 11揣炕、初始化其他的單例Bean(非延遲加載的)
finishBeanFactoryInitialization(beanFactory);
// 12帘皿、完成刷新過程,通知生命周期處理器lifecycleProcessor刷新過程,同時發(fā)出ContextRefreshEvent通知
finishRefresh();
}
catch (BeansException ex) {
// 13、銷毀已經(jīng)創(chuàng)建的Bean
destroyBeans();
// 14畸陡、重置容器激活標簽
cancelRefresh(ex);
throw ex;
}
finally {
resetCommonCaches();
}
}
}
這段代碼在前面的博客中已經(jīng)詳細的分析過了鹰溜,感興趣的同學查看前面的博客吧! 到這里Web應用上下文環(huán)境創(chuàng)建過程就結(jié)束了丁恭。