Spring 初始化过程详细分析[源码](一)

最近项目空闲期,来看下spring源码,把过程全部记录下来, 方便想了解spring初始化过程的人,先从spring监听器作为入口。

org.springframework.web.context.ContextLoaderListener

找到初始化spring的方法 

/**
	 * Initialize the root web application context.
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}

进入initWebApplicationContext 方法

			if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
				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);
					}
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}

进入createWebApplicationContext方法, 从方法名上就知道这是创建上下文的方法

/**
	 * Instantiate the root WebApplicationContext for this loader, either the
	 * default context class or a custom context class if specified.
	 * <p>This implementation expects custom contexts to implement the
	 * {@link ConfigurableWebApplicationContext} interface.
	 * Can be overridden in subclasses.
	 * <p>In addition, {@link #customizeContext} gets called prior to refreshing the
	 * context, allowing subclasses to perform custom modifications to the context.
	 * @param sc current servlet context
	 * @return the root WebApplicationContext
	 * @see ConfigurableWebApplicationContext
	 */
	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);
	}

进入determineContextClass方法, 这个方法确定上下文的实现类

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

这里先取web.xml中配置的contextClass值

例如:

<span style="white-space:pre">	</span><context-param>
		<param-name>contextClass</param-name>
		<param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
	</context-param>

如果为空,取默认策略属性的class,默认为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文件,在当前类同级目录,内容为

org.springframework.web.context.WebApplicationContext=org.springframework.web.context.support.XmlWebApplicationContext

前面key是接口,后面value是实现类.

好,这里完了,再看前面的createWebApplicationContext方法,这个方法返回了一个接口类ConfigurableWebApplicationContext, XmlWebApplicationContext实现了此接口

《Spring 初始化过程详细分析[源码](一)》

现在回到initWebApplicationContext方法, 看这句   if (this.context instanceof ConfigurableWebApplicationContext)  ,默认上下文会进入这个判断 

因为还没有初始化,判断为为空的都会进入,我们来看到这个方法 loadParentContext, 从方法上显然这是加载父上下文的,从servlet参数中(web.xml配置)加载父上下文, 如果需要多层结构才去配置,一般情况没有配置这里会返回空,我还没想到具体应用场景。先看下如何使用,看下面配置示例:

spring配置 beanRefContext.xml放在classpath目录下 ,内容:

<bean id="businessBeanFactory"  
                class="org.springframework.context.support.ClassPathXmlApplicationContext">  
                <constructor-arg>  
                        <list>  
                                <value>applicationContext-1.xml</value>  
                                <value>applicationContext-2.xml</value>   
                        </list>  
                </constructor-arg>  
        </bean>  

这个不配置默认查找 classpath*:beanRefContext.xml

<context-param>  
        <param-name>locatorFactorySelector</param-name>  
        <param-value>classpath:beanRefContext.xml</param-value>  
</context-param>
这个指定上面配置里的id
<context-param>  
        <param-name>parentContextKey</param-name>  
        <param-value>businessBeanFactory</param-value>  
</context-param>  

我们继续往下看,下个调用方法 configureAndRefreshWebApplicationContext(), 调用上下文刷新的方法。

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
		if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
			// The application context id is still set to its original default value
			// -> assign a more useful id based on available information
			String idParam = sc.getInitParameter(CONTEXT_ID_PARAM);
			if (idParam != null) {
				wac.setId(idParam);
			}
			else {
				// Generate default id...
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(sc.getContextPath()));
			}
		}

		wac.setServletContext(sc);
		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
		ConfigurableEnvironment env = wac.getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
		}

		customizeContext(sc, wac);
		wac.refresh();
	}

这个方法第一步先设置上下文id, 再读取web.xml中配置的contextConfigLocation参数值,进一步设置环境,并加载环境初始化参数(会取web.xml中读取,如果有配置的话)

customizeContext(sc, wac); 方法前主要是自定义初始化,只需要实现接口org.springframework.context.ApplicationContextInitializer<ConfigurableApplicationContext>

wac.refresh(); 这里才是真正加载xml配置, 这里调用了org.springframework.context.support.AbstractApplicationContext的refresh(),

这个方法具体做什么,等下章分解。

    原文作者:Spring Boot
    原文地址: https://blog.csdn.net/strivezxq/article/details/43795081
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞