spring源码解析(一):Spring启动流程

Spring启动流程

本系列文章是研究springMVC启动过程中spring是如何启动的,从读取web.xml,到IOC容器的生成、bean工厂的生成、bean的加载过程、bean的解析过程等等。

  1. spring启动流程简单介绍
  2. spring启动流程的核心refresh()方法简单介绍
  3. refresh()中的核心方法:obtainFreshBeanFactory()
  4. obtainFreshBeanFactory()中的具体方法解析:如何解析xml
  5. obtainFreshBeanFactory()中的具体方法解析:如何加载bean

1. Tomcat的启动,读取web.xml

tomcat启动时创建ServletContext(Servlet运行的上下文环境对象),读取web.xml,首先读取<context-param><listener>

  <!-- 配置 Spring -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>

  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  
  ...

ServletContext对象的使用

web应用参数可以让当前web应用的所有servlet获取,在web.xml文件中,<web-app>中进行配置:

  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:spring.xml</param-value>
  </context-param>

通过ServletContext获取web.xml中的参数:

String paramValue = context.getInitParameter("contextConfigLocation");
System.out.println("paramValue:"+paramValue);

//运行结果:
paramValue:classpath:spring.xml

2. 加载ContextLoader类的静态块

读取web.xml时,执行ContextLoaderListener监听器:

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

	public ContextLoaderListener() {
	}
	
	public ContextLoaderListener(WebApplicationContext context) {
		super(context);
	}

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

	/**
	 * Close the root web application context.
	 */
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		closeWebApplicationContext(event.getServletContext());
		ContextCleanupListener.cleanupAttributes(event.getServletContext());
	}
}

而ContextLoaderListener继承了ContextLoader类,实现了ServletContextListener接口。
因此在调用ContextLoaderListener监视器时先执行ContextLoader类的静态块:


public class ContextLoader {

    private static final String DEFAULT_STRATEGIES_PATH = "ContextLoader.properties";

	private static final Properties defaultStrategies;

	static {
		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());
		}
	}
}

执行代码块时会读取DEFAULT_STRATEGIES_PATH,即读取ContextLoader.properties文件,这个文件的内容:
在这里插入图片描述
点开内容为:

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

由此可见,这静态块的作用是设置defaultStrategies的默认值为XmlWebApplicationContext。

3. 初始化WebApplicationContext,具体步骤

执行完静态块,接下来执行ContextLoaderListener的contextInitialized方法。

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {

	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}
}

进入ContextLoader类的initWebApplicationContext方法,作用就是初始化根上下文WebApplicationContext,这是一个接口类,其实现类是XmlWebApplicationContext或AnnotationConfigWebApplicationContext。

public class ContextLoader {

    ...
    
    public WebApplicationContext initWebApplicationContext(ServletContext servletContext) {
    	//确保初始化一次,只有一个WebApplicationContext
		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!");
		}

		Log logger = LogFactory.getLog(ContextLoader.class);
		servletContext.log("Initializing Spring root WebApplicationContext");
		if (logger.isInfoEnabled()) {
			logger.info("Root WebApplicationContext: initialization started");
		}
		long startTime = System.currentTimeMillis();

		try {
			if (this.context == null) {
				//创建并初始化根上下文:WebApplicationContext
				this.context = createWebApplicationContext(servletContext);
			}
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
				if (!cwac.isActive()) {
					if (cwac.getParent() == null) {
						ApplicationContext parent = loadParentContext(servletContext);
						cwac.setParent(parent);
					}
					//完成所有bean的解析、加载和初始化
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}
			//将初始化后的context存到了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.isDebugEnabled()) {
				logger.debug("Published root WebApplicationContext as ServletContext attribute with name [" +
						WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE + "]");
			}
			if (logger.isInfoEnabled()) {
				long elapsedTime = System.currentTimeMillis() - startTime;
				logger.info("Root WebApplicationContext: initialization completed in " + elapsedTime + " ms");
			}

			return this.context;
		}
		catch (RuntimeException ex) {
			logger.error("Context initialization failed", ex);
			//即使初始化失败仍不允许有再次的初始化 
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
			throw ex;
		}
		catch (Error err) {
			logger.error("Context initialization failed", err);
			//即使初始化失败仍不允许有再次的初始化 
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, err);
			throw err;
		}
	}
	...
}

这个方法主要是做了四件事:

  1. 确保初始化一次,只有一个WebApplicationContext
  2. 创建并初始化根上下文:WebApplicationContext
  3. 完成所有bean的解析、加载和初始化
  4. 将WebApplicationContext放入ServletContext(Java Web的全局变量)中

3.1) 确保初始化一次,只有一个WebApplicationContext

初始化根上下文之前,首先判断是否有org.springframework.web.context.WebApplicationContext.ROOT。

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

注意:

String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";

调试发现:

ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE="org.springframework.web.context.WebApplicationContext.ROOT"

3.2) 创建并初始化根上下文:WebApplicationContext

    if (this.context == null) {
	    this.context = createWebApplicationContext(servletContext);
	}

createWebApplicationContext方法:

	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
		// 确定上下文类是XmlWebApplicationContext或AnnotationConfigWebApplicationContext
		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);
			}
		}
	}

其中

	public static final String CONTEXT_CLASS_PARAM = "contextClass";
	
	...
	
	String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);

优先从ServletContext取contextClass参数对应的值,即查看是否在web.xml中配置
,从而判断获取contextClassName的值是否为空。

  1. 如果contextClassName不为null,则加载web.xml中配置的参数
  2. 如果contextClassName为null,则加载默认的XmlWebApplicationContext
	contextClassName = defaultStrategies.getProperty(WebApplicationContext.class.getName());

其中defaultStrategies是在ContextLoader类中执行静态块设置的默认:XmlWebApplicationContext,因此WebApplicationContext的实现类是XmlWebApplicationContext。

3.3) 完成所有bean的解析、加载和初始化

因为XmlWebApplicationContext间接实现了ConfigurableWebApplicationContext接口,所以执行以下代码:

if (this.context instanceof ConfigurableWebApplicationContext) {
	ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
	//初始化的时候容器还未刷新
	if (!cwac.isActive()) {
		if (cwac.getParent() == null) {
			ApplicationContext parent = loadParentContext(servletContext);
						cwac.setParent(parent);
		}
		configureAndRefreshWebApplicationContext(cwac, servletContext);
	}
}

configureAndRefreshWebApplicationContext方法:

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
		if (ObjectUtils.identityToString(wac).equals(wac.getId())) {
			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()));
			}
		}
		//将servletContext这个上下文放到了wac中
		//在Spring容器中,有了servlet的上下文参数,那么我们可以在spring后续的容器操作中,使用servlet的配置等信息了
		wac.setServletContext(sc);
		
		//读取web.xml中Spring配置文件路径
		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();
	}

读取web.xml中定义的context-param:contextConfigLocation来找到spring的配置文件

String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
//configLocationParam = "classpath:spring.xml"
//见web.xml中配置

其中sc为ServletContext,CONFIG_LOCATION_PARAM=“contextConfigLocation”。

重点来了,wac.refresh(),这个方法就要开始Spring容器的刷新了

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			//1 刷新前的预处理
			prepareRefresh();
            //2 获取BeanFactory;刚创建的默认DefaultListableBeanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
            //3 BeanFactory的预准备工作(BeanFactory进行一些设置)
			prepareBeanFactory(beanFactory);

			try {
		    	// 4 BeanFactory准备工作完成后进行的后置处理工作;
				postProcessBeanFactory(beanFactory);
 /**************************以上是BeanFactory的创建及预准备工作  ****************/
 
                // 5 执行BeanFactoryPostProcessor的方法;
				invokeBeanFactoryPostProcessors(beanFactory);
               
                //6 注册BeanPostProcessor(Bean的后置处理器)
				registerBeanPostProcessors(beanFactory);
                
                 // 7 initMessageSource();初始化MessageSource组件(做国际化功能;消息绑定,消息解析);
				initMessageSource();
                
                 // 8 初始化事件派发器
				initApplicationEventMulticaster();
               
                // 9 子类重写这个方法,在容器刷新的时候可以自定义逻辑;
				onRefresh();
               
                // 10 给容器中将所有项目里面的ApplicationListener注册进来
				registerListeners();

                // 11.初始化所有剩下的单实例bean;
				finishBeanFactoryInitialization(beanFactory);

                 // 12.完成BeanFactory的初始化创建工作;IOC容器就创建完成;
				finishRefresh();
			}
			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				destroyBeans();

				cancelRefresh(ex);

				throw ex;
			}
            ...
		}
	}

3.4) 将初始化后的context存到了servletContext中

初始化完成的context(XmlWebApplicationContext或AnnotationConfigWebApplicationContext)存到了一个Map变量中,key值就是WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE这个常量,目的是为了避免再被初始化。

servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);

注意:

String ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE = WebApplicationContext.class.getName() + ".ROOT";

调试发现:

ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE="org.springframework.web.context.WebApplicationContext.ROOT"

spring启动流程 viso流程图下载地址:
https://download.csdn.net/download/u011151359/11500967

下一章:spring源码解析(二):refresh()源码解析

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值