一:創建業務容器
ContextLoaderListener配置在web.xml中,主要是爲了創建springmvc中的容器。在springmvc項目啓動時需要啓動創建一個容器,加載各種組件。那麼ContextLoaderListener的contextInitialized就是這個容器開始的地方
web.xml的配置
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
contextInitialized方法入口:
public void contextInitialized(ServletContextEvent event) {
//初始化容器
initWebApplicationContext(event.getServletContext());
}
initWebApplicationContext方法是ContextLoaderListener是繼承父類ContextLoader的方法。
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 {
if (this.context == null) {
//創建容器
this.context = createWebApplicationContext(servletContext);
}
if (this.context instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
if (!cwac.isActive()) {
//加載父ApplicationContext
if (cwac.getParent() == null) {
ApplicationContext parent = loadParentContext(servletContext);
cwac.setParent(parent);
}
//配置並刷新WebApplicationContext
configureAndRefreshWebApplicationContext(cwac, servletContext);
}
}
//將WebApplicationContext設置進入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.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;
}
}
在這個邏輯中其實就分爲三步,並不是很複雜。
- 創建容器
- 配置並刷新容器
- 將容器設置進入WebApplicationContext
第一步:創建容器
protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
//判斷創建什麼類型的容器
Class<?> contextClass = determineContextClass(sc);
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
}
//這個就是反射 創建容器了
return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
}
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 {
//沒有自定義的配置,獲取默認的容器類型。 默認類型爲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);
}
}
}
創建容器的過程看起來不是很複雜的,首先先判斷容器是什麼類型的容器(當然我們一般默認是通過xml文件創建的),再根據反射來獲取得到這個容器。整個過程並不是很複雜。下面來分析下配置和刷新容器
protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
//從ServletContext中獲取用戶配置的contextId屬性
String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
if (idParam != null) {
//不爲空 設置容器Id
wac.setId(idParam);
}
else {
// 設置默認的容器id org.springframework.web.context.WebApplicationContext:#DisplayName#
wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
ObjectUtils.getDisplayString(sc.getContextPath()));
}
}
wac.setServletContext(sc);
//獲取contextConfigLocation的配置
String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
if (configLocationParam != null) {
wac.setConfigLocation(configLocationParam);
}
//獲取對應的環境。對於開發我們分爲開發、測試、生產環境。 不同的環境需要加載不同的配置文件信息。
ConfigurableEnvironment env = wac.getEnvironment();
if (env instanceof ConfigurableWebEnvironment) {
((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
}
customizeContext(sc, wac);
//刷新容器
wac.refresh();
}
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//初始化context上下文環境等
prepareRefresh();
//創建一個beanFactory工廠
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//配置工廠的標準環境
prepareBeanFactory(beanFactory);
try {
postProcessBeanFactory(beanFactory);
//調用所有的bean工廠處理器(BeanFactoryPostProcessor)對bean工廠進行一些處理。這個方法必須在所有的singleton初始化之前調用
invokeBeanFactoryPostProcessors(beanFactory);
//註冊後置通知器
registerBeanPostProcessors(beanFactory);
//初始化MessageSource接口的一個實現類。這個接口提供了消息處理功能。主要用於國際化/i18n。
initMessageSource();
//爲這個context初始化一個事件廣播器(ApplicationEventMulticaster)
initApplicationEventMulticaster();
//初始化ThemeSource接口的實例
onRefresh();
//註冊監聽器
registerListeners();
//完成bean工廠的初始化工作,創建bean
finishBeanFactoryInitialization(beanFactory);
//完成context的刷新
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
//如果刷新失敗那麼就會將已經創建好的單例Bean銷燬掉
destroyBeans();
cancelRefresh(ex);
throw ex;
}
finally {
//清除緩存
resetCommonCaches();
}
}
}
- 設置容器 id
- 獲取 contextConfigLocation 配置,並設置到容器中
- 刷新容器
這個方法的邏輯也不是很複雜的邏輯,整體也就是這個三個重要的方法。
二:創建Web容器
web容器的創建其實是在初始化DispatcherServlet類時,通過其父類HttpServletBean覆蓋了HttpServlet的init方法來創建Web容器
public final void init() throws ServletException {
if (logger.isDebugEnabled()) {
logger.debug("Initializing servlet '" + getServletName() + "'");
}
//將Servlet中配置的參數封裝到PropertyValues中
PropertyValues pvs = new ServletConfigPropertyValues(getServletConfig(), this.requiredProperties);
if (!pvs.isEmpty()) {
try {
BeanWrapper bw = PropertyAccessorFactory.forBeanPropertyAccess(this);
//加載xml文件
ResourceLoader resourceLoader = new ServletContextResourceLoader(getServletContext());
bw.registerCustomEditor(Resource.class, new ResourceEditor(resourceLoader, getEnvironment()));
initBeanWrapper(bw);
//設置配置信息到目標對象中
bw.setPropertyValues(pvs, true);
}
catch (BeansException ex) {
if (logger.isErrorEnabled()) {
logger.error("Failed to set bean properties on servlet '" + getServletName() + "'", ex);
}
throw ex;
}
}
// 子類初始化的入口 frameworkServlet
initServletBean();
if (logger.isDebugEnabled()) {
logger.debug("Servlet '" + getServletName() + "' configured successfully");
}
}
這裏提供了三個類的簡介
- PropertyValues:獲取Web.xml裏面的servlet的init-param(web.xml)
- BeanWrapper:封裝了bean的行爲,提供了設置和獲取屬性值,它有對應的BeanWrapperImpl
- ResourceLoader:接口僅有一個getResource(String location)的方法,可以根據一個資源地址加載文件資源。
所以大致的思路:先通過PropertyValues獲取web.xml文件init-param的參數值,然後通過ResourceLoader讀取.xml配置信息,BeanWrapper對配置的標籤進行解析和將系統默認的bean的各種屬性設置到對應的bean屬性。
protected WebApplicationContext initWebApplicationContext() {
//獲取ContextLoaderListener創建的容器
WebApplicationContext rootContext =
WebApplicationContextUtils.getWebApplicationContext(getServletContext());
WebApplicationContext wac = null;
if (this.webApplicationContext != null) {
// A context instance was injected at construction time -> use it
wac = this.webApplicationContext;
if (wac instanceof ConfigurableWebApplicationContext) {
ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) wac;
if (!cwac.isActive()) {
if (cwac.getParent() == null) {
//設置父容器
cwac.setParent(rootContext);
}
//配置並刷新容器
configureAndRefreshWebApplicationContext(cwac);
}
}
}
if (wac == null) {
//Servlet不是由編程式註冊到容器中,查找servletContext中已經註冊的WebApplicationContext作爲上下文
wac = findWebApplicationContext();
}
if (wac == null) {
//如果都沒找到時,就用根上下文就創建一個上下文有ID
wac = createWebApplicationContext(rootContext);
}
if (!this.refreshEventReceived) {
//在上下文關閉的情況下調用refesh可啓動應用上下文,在已經啓動的狀態下,調用refresh則清除緩存並重新裝載配置信息
onRefresh(wac);
}
//對不同的請求對應的DispatherServlet有不同的WebApplicationContext、並且都存放在ServletContext中
if (this.publishContext) {
String attrName = getServletContextAttributeName();
getServletContext().setAttribute(attrName, wac);
if (this.logger.isDebugEnabled()) {
this.logger.debug("Published WebApplicationContext of servlet '" + getServletName() +
"' as ServletContext attribute with name [" + attrName + "]");
}
}
return wac;
}
protected WebApplicationContext createWebApplicationContext(@Nullable ApplicationContext parent) {
//獲取容器的類型
Class<?> contextClass = getContextClass();
if (this.logger.isDebugEnabled()) {
this.logger.debug("Servlet with name '" + getServletName() +
"' will try to create custom WebApplicationContext context of class '" +
contextClass.getName() + "'" + ", using parent context [" + parent + "]");
}
if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
throw new ApplicationContextException(
"Fatal initialization error in servlet with name '" + getServletName() +
"': custom WebApplicationContext class [" + contextClass.getName() +
"] is not of type ConfigurableWebApplicationContext");
}
//反射創建容器
ConfigurableWebApplicationContext wac =
(ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
wac.setEnvironment(getEnvironment());
wac.setParent(parent);
String configLocation = getContextConfigLocation();
if (configLocation != null) {
wac.setConfigLocation(configLocation);
}
//配置並刷新
configureAndRefreshWebApplicationContext(wac);
return wac;
}
創建Web容器的過程大致就是上面的邏輯。
- 從 ServletContext 中獲取 ContextLoaderListener 創建的容器
- 若 this.webApplicationContext != null 條件成立,僅設置父容器和刷新容器即可
- 嘗試從 ServletContext 中獲取容器,若容器不爲空,則無需執行步驟4
- 創建容器,並將 rootContext 作爲父容器
- 設置容器到 ServletContext 中
在onRefresh()方法則交由DispatcherServlet去實現加載不同的web組件代碼如下:
protected void initStrategies(ApplicationContext context) {
//初始化上傳文件解析器
initMultipartResolver(context);
//初始化本地解析器
initLocaleResolver(context);
//初始化主題解析器
initThemeResolver(context);
//初始化映射處理器
initHandlerMappings(context);
//初始化適配器處理器
initHandlerAdapters(context);
//初始化異常處理器
initHandlerExceptionResolvers(context);
//初始化請求到視圖名翻譯器
initRequestToViewNameTranslator(context);
//初始化視圖解析器
initViewResolvers(context);
initFlashMapManager(context);
}