Spring容器启动流程

简单分析解读一下Web容器启动时Spring容器的初始化过程

1 启动web容器

web容器启动时读取web.xml,如下

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <!-- needed for ContextLoaderListener -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>

	<!-- Bootstraps the root web application context before servlet initialization -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
	
	<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
	<servlet>
		<servlet-name>springDispatcherServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<load-on-startup>1</load-on-startup>
	</servlet>
	
</web-app>

web容器的初始化过程为:

  • 读取web.xml文件
  • web容器创建servlet上下文对象(servletContext)
  • 读取context-param节点并转化为键值对的形式传给servletContext
  • 读取linstener节点的监听器,其中接节点中的监听器类必须实现ServletContextListener接口
  • 执行监听器中从ServletContextListener接口实现的contextInitialized()方法
    ServletContextListener接口能监听整个servletContext的生命周期,也就是web容器的生命周期,当web容器启动或关闭时都会触发ServletContextEvent事件,然后由ServletContextListener来处理。其中容器启动调用contextInitialized()方法,关闭调用contextDestroyed()方法

2 initWebApplicationContext()

进入listener节点中的ContextLoaderListener类中

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
	/**
	 * 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类并且实现了ServletContextListeneri接口
在contextInitialized()中调用了initWebApplicationContext()方法,并且由event对象传入了servletContext对象
整个Spring容器的初始化也就是在这个方法中完成

进入initWebApplicationContext()

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!");
		}
		//打印日志并开始计算启动时间
		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 {
			//创建WebApplicationContext
			if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
			// 判断context有没有父context,取决于web.xml配置文件中locatorFactorySelector参数,如果有父context,则加载它
			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);
					}
					// refresh容器,最重要的一步,这一步会创建beans
					configureAndRefreshWebApplicationContext(cwac, servletContext);
				}
			}
			//把当前Spring的容器对象放到全局的Servlet容器(ServletContext)中
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, this.context);
			//将spring容器context赋值给currentContext变量,保存下来
			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 创建web环境下的Spring容器实现类WebApplicationContext,通过createWebApplicationContext()
2 加载配置文件,初始化Spring容器,通过configureAndRefreshWebApplicationContext()方法
3 把Spring容器对象放到Servlet上下文对象中,通过servletContext.setAttribute()

3 createWebApplicationContext() 创建Spring容器

protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
		//获取WebApplicationContext实现类的class对象,通过determineContextClass()
		Class<?> contextClass = determineContextClass(sc);
		//获取的WebApplicationContext实现类必须继承自ConfigurableWebApplicationContext
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
					"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
		}
		//根据calss对象创建实例对象
		return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
	}

创建Spring是通过WebApplicationContext的实现类的class对象创建的实例对象
接下来进入determineContextClass()看一下怎么获取的class对象

protected Class<?> determineContextClass(ServletContext servletContext) {
		//获取web.xml中name为contextClass的context-param节点的的值
		String contextClassName = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
		//如果在web.xml中配置了contextClass节点则直接根据类名来创建容器
		if (contextClassName != null) {
			try {
				return ClassUtils.forName(contextClassName, ClassUtils.getDefaultClassLoader());
			}
			catch (ClassNotFoundException ex) {
				throw new ApplicationContextException(
						"Failed to load custom context class [" + contextClassName + "]", ex);
			}
		}
		//如果没有配置contextClass,则创建Spring在web环境下的默认容器
		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);
			}
		}
	}

defaultStrategies的声明和上面这些方法一样都在ContexLoader类中,看下面

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

在ContextLoader中直接声明了一个静态代码块对defaultStrategies进行了初始化
根据DEFAULT_STRATEGIES_PATH这个静态常量作为路径读取配置的properties文件然后加载这个文件
路径直接时文件名所以文件就在ContextLoader这个类的同路径下,直接找到ContextLoader.properties打开

# Default WebApplicationContext implementation class for ContextLoader.
# Used as fallback when no explicit context implementation has been specified as context-param.
# Not meant to be customized by application developers.

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

只有一句话,指明了Spring的容器初始化类为XmlWebApplicationContext,也就是说,Spring在Web环境下的初始化类就是XmlWebApplicationContext

4 configureAndRefreshWebApplicationContext() 主要初始化方法

创建Spring容器之后就会加载Spring的配置文件并根据配置文件初始化Beans,整个过程就是在configureAndRefreshWebApplicationContext()中
进入configureAndRefreshWebApplicationContext()方法

protected void configureAndRefreshWebApplicationContext(ConfigurableWebApplicationContext wac, ServletContext sc) {
		//设置容器Id
		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()));
			}
		}
		//把Servlet容器设置到Spring容器中
		wac.setServletContext(sc);
		//获取Web.xml中name为contextConfigLocation的context-param节点的值
		//public static final String CONFIG_LOCATION_PARAM = "contextConfigLocation"
		String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
		//如果配置了contextConfigLocation则直接作为路径加载配置文件
		if (configLocationParam != null) {
			wac.setConfigLocation(configLocationParam);
		}

		//初始化Servlet的propertySources
		ConfigurableEnvironment env = wac.getEnvironment();
		if (env instanceof ConfigurableWebEnvironment) {
			((ConfigurableWebEnvironment) env).initPropertySources(sc, null);
		}
		//个性化配置,一般用默认即可
		customizeContext(sc, wac);
		//主要工作就是在这里完成
		wac.refresh();
	}

configureAndRefreshWebApplicationContext()会先读取web.xml中声明的contextConfigLocation的值,通过它来找到Spring的配置文件,然后在最后的refresh()中读取配置文件,并初始化和创建Beans,接下来进入refresh()

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) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}
				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();
				// Reset 'active' flag.
				cancelRefresh(ex);
				// Propagate exception to caller.
				throw ex;
			}
			finally {
				resetCommonCaches();
			}
		}
	}

refresh()的方法有很多也很复杂,在下一篇文章里再进行详细的分析

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值