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

之前我们查看了初始化流程的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
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

xlecho

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值