Spring启动过程的追踪(一)-refresh方法的触发时机

Spring启动过程追踪

闲来无事,想着把spring工作机制梳理梳理,当下spring框架确实是非常牛逼的存在,扩展了很多模块,springboot springcloud springsecurity等都是spring衍生出来的

在这里插入图片描述

web容器启动

WEB项目启动时候,会加载web.xml文件,在web.xml中配置了ContextLoaderListener(监听器),下面分析下这个监听器对象

1、ContextLoaderListener类信息

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
..
	/**
	 * 初始化web上下文环境
	 */
	@Override
	public void contextInitialized(ServletContextEvent event) {
		initWebApplicationContext(event.getServletContext());
	}

	/**
	 * 关闭web容器
	 */
	@Override
	public void contextDestroyed(ServletContextEvent event) {
		closeWebApplicationContext(event.getServletContext());
		ContextCleanupListener.cleanupAttributes(event.getServletContext());
	}

}

2、initWebApplicationContext(event.getServletContext());初始化方法

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!");
		}
	    ......
			if (this.context == null) {
			    //创建web环境
				this.context = createWebApplicationContext(servletContext);
			}
		.......
		//配置spring配置文件
		String configLocationParam = sc.getInitParameter(CONFIG_LOCATION_PARAM);
		if (configLocationParam != null) {
			wac.setConfigLocation(configLocationParam);
		}
		   //刷新容器
		   configureAndRefreshWebApplicationContext(cwac, servletContext);

			return this.context;
		}
	
	}

3、createWebApplicationContext(servletContext);

	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
		Class<?> contextClass = determineContextClass(sc);
		...
		return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
	}

4、determineContextClass(sc);

在这里插入图片描述
注意:defaultStrategies是配置文件资源信息,见下图
在这里插入图片描述
contextLoader.properties配置文件在spring-web的jar包中的位置如下图
在这里插入图片描述
我们稍微看一眼这个配置文件中是啥哈
在这里插入图片描述
默认是XmlWebApplicationContext

至此,XmlWebApplicationContext被创建对象完成,回到 2步骤中的initWebApplicationContext方法,可以看到,会进行容器刷新操作

configureAndRefreshWebApplicationContext(cwac, servletContext);

进入方法会发现 wac.refresh();被调用,即XmlWebApplicationContext的refresh方法触发

总结:本文简单说明了spring默认xml配置方法的上下文环境启动的前奏,当然现在大多数是注解形式的,这个在代码中有所表示,我们可以配置在web.xml中,初始化参数配置中添加contextClass 节点 为AnnotationConfigApplicationContext即可

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值