SpringBoot源码第三章-refreshContext

refreshContext() 刷新上下文

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

@Override
	public void refresh() throws BeansException, IllegalStateException {
		this.startupShutdownLock.lock();
		try {
			this.startupShutdownThread = Thread.currentThread();

			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			// 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);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);
				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);
				beanPostProcess.end();

				// 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 (RuntimeException | Error 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 {
				contextRefresh.end();
			}
		}
		finally {
			this.startupShutdownThread = null;
			this.startupShutdownLock.unlock();
		}
	}

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

obtainFreshBeanFactory()

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		refreshBeanFactory();
		return getBeanFactory();
	}

refreshBeanFactory()方法是AbstractApplicationContext中的抽象方法,AbstractRefreshableApplicationContext是xml配置文件类型的中实现,GenericApplicationContext是其注解版的实现,该方法最终的返回实现子类是,DefaultListableBeanFactory,在springboot中的GenericApplicationContext的代码如下

	@Override
	protected final void refreshBeanFactory() throws IllegalStateException {
		if (!this.refreshed.compareAndSet(false, true)) {
			throw new IllegalStateException(
					"GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
		}
		this.beanFactory.setSerializationId(getId());
	}

类的继承图如下

prepareBeanFactory(beanFactory)方法

装填beanFactory工厂的各种属性值

posted @   浪成于微澜之间  阅读(57)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示