一:创建业务容器
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);
}