SpringBoot源码第三章-refreshContext

发布时间 2023-07-24 11:32:17作者: 浪成于微澜之间

refreshContext() 刷新上下文

private void refreshContext(ConfigurableApplicationContext context) {
    /**
      * cintext = AnnotationConfigApplicationContext
      */
      refresh(context);
      if (this.registerShutdownHook) {
	try {
		context.registerShutdownHook();
	}catch (AccessControlException ex) {
	// Not allowed in some environments.
	}
    }
}

这里的参数context传的是AnnotationConfigApplicationContext类的继承图如下

调用refresh()方法

protected void refresh(ApplicationContext applicationContext) {
		Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
		((AbstractApplicationContext) applicationContext).refresh();
	}

这里的refresh()调用的spring源码中的spring-context中的内容,也是spring框架bean装载的核心

	@Override
	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 {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

prepareRefresh()方法

protected void prepareRefresh() {
	// IOC容器启动时间
	this.startupDate = System.currentTimeMillis();
        //容器标识  
	this.closed.set(false);
        //容器激活标识  
	this.active.set(true);

	if (logger.isDebugEnabled()) {
	  if (logger.isTraceEnabled()) {
		logger.trace("Refreshing " + this);
	    }else {
		logger.debug("Refreshing " + getDisplayName());
	    }
	}

	// 留给子类实现,初始化系统资源
	initPropertySources();

	// Validate that all properties marked as required are resolvable:
	// 创建并获取环境对象,验证需要的属性文件是否都放入到环境中
	getEnvironment().validateRequiredProperties();

	// 判断刷新前的应用程序监听器集合是否为空,如果为空,则将监听器添加到此集合中
	if (this.earlyApplicationListeners == null) {
		this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
	}else {
	  // 如果不等于空,则清空集合元素对象
	  this.applicationListeners.clear();
	  this.applicationListeners.addAll(this.earlyApplicationListeners);
	}

	// Allow for the collection of early ApplicationEvents,
	// 创建刷新前的监听事件集合
	this.earlyApplicationEvents = new LinkedHashSet<>();
}