【Spring源码这样读】-细扒ApplicationContext之prepareRefresh()

原创
2021/04/21 10:21
阅读数 77

之前我们查看了初始化流程的super(parent)和setConfigLocations(configLocations),接下来我们进入最重要的环节refresh()方法,这个方法,才是我们spring初始化容器的最关键的方法。我们将一步一步细读,大佬略过。

refresh()

这个方法主要做了一下这几件事情:

  • 容器刷新前的准备
  • 初始化beanFactory,加载并解析配置
  • 设置beanFactory的属性
  • BeanFactory创建完成后进行的后置处理工作
  • 执行BeanFactoryPostProcessor的方法
  • 注册BeanPostProcessor
  • 初始化MessageSource组件
  • 初始化事件派发器
  • 子类重写这个方法,在容器刷新的时候可以自定义逻辑
  • 给容器中将所有项目里面的ApplicationListener注册进来
  • 初始化所有剩下的单实例bean
  • 完成BeanFactory的初始化创建工作,IOC容器就创建完成

这里我们先来看看容器刷新前做了些什么吧

prepareRefresh()

方法的源码并不多,如下:

protected void prepareRefresh() {
	// Switch to active.
	// 这一句很明显的获取了系统当前时间,其实他的作用是来记录当前的启动时间的
	this.startupDate = System.currentTimeMillis();
	
	// 这两个状态的设置,前者关闭程序设置为false,后者运行标识设置为true
	this.closed.set(false);
	this.active.set(true);

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

	// Initialize any placeholder property sources in the context environment.
	// 目前还是一个空方法,应该后面会补充
	initPropertySources();

	// Validate that all properties marked as required are resolvable:
	// see ConfigurablePropertyResolver#setRequiredProperties
	// 校验 xml配置文件
	getEnvironment().validateRequiredProperties();

	// Store pre-refresh ApplicationListeners...
	// 判断刷新前的运用程序监听集合是否为空,为空初始化applicationListeners监听,不为空,则清空监听器
	if (this.earlyApplicationListeners == null) {
		this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
	}
	else {
		// Reset local application listeners to pre-refresh state.
		this.applicationListeners.clear();
		this.applicationListeners.addAll(this.earlyApplicationListeners);
	}

	// Allow for the collection of early ApplicationEvents,
	// to be published once the multicaster is available...
	// 创建刷新前的事件集合
	this.earlyApplicationEvents = new LinkedHashSet<>();
}

这个方法prepareRefresh(),是在spring5.3之后加了程序,所以之前的版本是没有办法看到的。

就做了这几件事情

  • 设置容器的启动时间
  • 设置活跃状态为true
  • 设置关闭状态为false
  • 获取Environment对象,并加载当前系统的环境到Environment中
  • 准备监听器和事件的集合对象,默认为空
展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部