spring-加载入口

spring-加载入口

版本:5.2.8

ContextLoaderListener

实现了ServletContextListener接口,可以在ServletContext创建时执行contextInitialized方法;

继承了ContextLoader类,主要的业务逻辑写在这个父类中,此处没有放到一个类中写,做到了分离;

public void contextInitialized(ServletContextEvent event) {
    // 调用父类方法
	initWebApplicationContext(event.getServletContext());
}

在这里插入图片描述

ContextLoader

初始化

类加载的时候执行的初始化,加载当前类路径的一个名为ContextLoader.properties文件到defaultStrategies里;

	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.properties文件内容,其实就是配置WebApplicationContext的实现类;

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

initWebApplicationContext()

	public WebApplicationContext initWebApplicationContext(ServletContext 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!");
		}

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

		try {
			// 构建WebApplicationContext
			if (this.context == null) {
				this.context = createWebApplicationContext(servletContext);
			}
             // 由上一步可以知道是ConfigurableWebApplicationContext的实现类
			if (this.context instanceof ConfigurableWebApplicationContext) {
				ConfigurableWebApplicationContext cwac = (ConfigurableWebApplicationContext) this.context;
                 // 现在是不活跃的状态
				if (!cwac.isActive()) {
					// 默认是空的
					if (cwac.getParent() == null) {
						// 此处返回的也是null
						ApplicationContext parent = loadParentContext(servletContext);
						cwac.setParent(parent);
					}
                      // 实际的加载处理在这个方法中
					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.isInfoEnabled()) {
				long elapsedTime = System.currentTimeMillis() - startTime;
				logger.info("Root WebApplicationContext initialized in " + elapsedTime + " ms");
			}

			return this.context;
		}
		catch (RuntimeException | Error ex) {
			logger.error("Context initialization failed", ex);
			servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE, ex);
			throw ex;
		}
	}

createWebApplicationContext()

	protected WebApplicationContext createWebApplicationContext(ServletContext sc) {
         // 决定使用用户配置的实现类还是ContextLoader.properties中配置的实现类
		Class<?> contextClass = determineContextClass(sc);
         // 当前的contextClass是不是ConfigurableWebApplicationContext的实现类,通过下图的类结构能判断出是这个接口的实现类
		if (!ConfigurableWebApplicationContext.class.isAssignableFrom(contextClass)) {
			throw new ApplicationContextException("Custom context class [" + contextClass.getName() +
					"] is not of type [" + ConfigurableWebApplicationContext.class.getName() + "]");
		}
         // 这里返回了一个ConfigurableWebApplicationContext类型的WebApplicationContext
		return (ConfigurableWebApplicationContext) BeanUtils.instantiateClass(contextClass);
	}

determineContextClass()

	protected Class<?> determineContextClass(ServletContext servletContext) {
    	// 从web.xml中查找是否在<context-param>标签的<param-name>中配置了contextClass,一般不配置
		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 {
             // 此处就是从ContextLoader.properties文件中获取的具体实现类
			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);
			}
		}
	}

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 {
				wac.setId(ConfigurableWebApplicationContext.APPLICATION_CONTEXT_ID_PREFIX +
						ObjectUtils.getDisplayString(sc.getContextPath()));
			}
		}

		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);
         // 加载bean
		wac.refresh();
	}

XmlWebApplicationContext

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值