Spring初始化 - XmlWebApplicationContext

本文详细介绍了Spring框架中XmlWebApplicationContext的初始化过程,包括实例化、配置、刷新等关键步骤,并深入探讨了配置文件的加载机制。

一.概述
XmlWebApplicationContext是Spring在web应用中的context,ApplicationContext是Spring的核心,context通常解释为上下文环境,用“容器”来表述它更容易理解一些,ApplicationContext则是“应用的容器”了



二.XmlWebApplicationContext初始流程


1.XmlWebApplicationContext实例化

org.springframework.web.context.ContextLoader # createWebApplicationContext(ServletContext sc)调用无参构造函数实例化了XmlWebApplicationContext,但是XmlWebApplicationContext还没有配置了刷新

	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);
	}

2.配置和刷新XmlWebApplicationContext

org.springframework.web.context.ContextLoader # configureAndRefreshWebApplicationContext()主要处理上下文wac的属性和刷新
1.设置wac的id、Spring xml配置文件路径以及将上下文wac记录到web容器上下文sc中
2.wac刷新:wac.refresh()
    /** 
     * 配置XmlWebApplicationContext,读取web.xml中通过contextConfigLocation标签指定的XML文件, 
     * 实例化XML文件中配置的bean,并在上一步中实例化的容器中进行注册。 
     */  
    protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {  
        /** 
         * ObjectUtils.identityToString(wac):对象wac的String表示, 
         *                                  如org.springframework.web.context.support.XmlWebApplicationContext@1e8bf76 
         * wac.getId():上下文的唯一id,     如org.springframework.web.context.support.XmlWebApplicationContext@1e8bf76 
         */   
        if (ObjectUtils.identityToString(wac).equals(wac.getId())) {  
            // 获取web容器上下文中的Spring上下文contextId  
            String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);  
            if (idParam != null) {  
                // 如果idParam已存在,wac id还是设置为原始值idParam  
                wac.setId(idParam);  
            } else {  
                // 根据可用信息分配一个更有用的ID  
                // 如org.springframework.web.context.WebApplicationContext:/bi  
                if (sc.getMajorVersion() == 2 && sc.getMinorVersion() < 5) {  
                    // Servlet <= 2.4: resort to name specified in web.xml, if any.  
                    wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +  
                            ObjectUtils.getDisplayString(sc.getServletContextName()));  
                } else {  
                    wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +  
                            ObjectUtils.getDisplayString(sc.getContextPath()));  
                }  
            }  
        }  
        // 将web容器上下文对象记录在Spring上下文中  
        wac.setServletContext(sc);  
        // 返回自定义Spring配置文件路径:如/WEB-INF/spring/applicationContext.xml  
        String initParameter = sc.getInitParameter(CONFIG_LOCATION_PARAM);  
        if (initParameter != null) {  
            // 记录配置xml,可能有多个  
            wac.setConfigLocation(initParameter);  
        }  
        customizeContext(sc, wac);  
        // 刷新上下文  
        wac.refresh();  
    }  

3.XmlWebApplicationContext刷新

org.springframework.context.support.AbstractApplicationContext #refresh() 方法处理ApplicationContext的刷新

	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				finishRefresh();
			} catch (BeansException ex) {
				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}
		}
	}

4.下一篇

上下文刷新

三.源码

package org.springframework.web.context.support;

import java.io.IOException;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.ResourceEntityResolver;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;

/**
 * 1. 默认情况下,root context将从"/WEB-INF/applicationContext.xml"中获取配置信息
 *
 * 2. 默认配置位置可以被web.xml中<context-param>"contextConfigLocation"覆盖
 *    <context-param>  
 *      <param-name>contextConfigLocation</param-name>  
 *      <param-value>/WEB-INF/spring/applicationContext.xml</param-value>  
 *    </context-param> 
 */
public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationContext {

	// root context的默认配置位置
	public static final String DEFAULT_CONFIG_LOCATION = "/WEB-INF/applicationContext.xml";

	// 默认配置位置的前缀
	public static final String DEFAULT_CONFIG_LOCATION_PREFIX = "/WEB-INF/";

	// 默认配置位置的后缀
	public static final String DEFAULT_CONFIG_LOCATION_SUFFIX = ".xml";

	/**
	 * 通过XmlBeanDefinitionReader加载bean定义。
	 * @see org.springframework.beans.factory.xml.XmlBeanDefinitionReader
	 */
	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// 为给定的beanFactory创建一个新的XmlBeanDefinitionReader
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
		
		//允许子类提供beanDefinitionReader的自定义初始化,然后继续实际加载bean定义。
		initBeanDefinitionReader(beanDefinitionReader);
		// 使用给定的reader加载bean定义
		loadBeanDefinitions(beanDefinitionReader);
	}

	/**
	 * beanDefinitionReader的自定义实例化,默认为空
	 * @param beanDefinitionReader the bean definition reader used by this context
	 */
	protected void initBeanDefinitionReader(XmlBeanDefinitionReader beanDefinitionReader) {
	}

	/**
	 * 使用给定的reader加载bean定义
	 * bean工厂的生命周期由refreshBeanFactory方法处理,因此这个方法只是加载和/或注册bean定义。
	 * 子类方法org.springframework.context.support.AbstractRefreshableApplicationContext# refreshBeanFactory()
	 *
	 * 将ResourcePatternResolver的代表用于将位置模式解析为资源实例。
	 */
	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			for (String configLocation : configLocations) {
				reader.loadBeanDefinitions(configLocation);
			}
		}
	}

	/**
	 * root context的默认配置位置为“/WEB-INF/applicationContext.xml”
	 * namespace为"test-servlet"的context的默认配置位置为"/WEB-INF/test-servlet.xml"
	 * The default location for the root context is "/WEB-INF/applicationContext.xml",
	 * and "/WEB-INF/test-servlet.xml" for a context with the namespace "test-servlet"
	 * (like for a DispatcherServlet instance with the servlet-name "test").
	 */
	@Override
	protected String[] getDefaultConfigLocations() {
		if (getNamespace() != null) {
			return new String[] {DEFAULT_CONFIG_LOCATION_PREFIX + getNamespace() + DEFAULT_CONFIG_LOCATION_SUFFIX};
		} else {
			return new String[] {DEFAULT_CONFIG_LOCATION};
		}
	}

}











评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值