Spring启动--PrepareRefresh方法!最最最!详解

prepareRefresh();    //准备工作  初始化spring状态 使spring处于运行状态

  • 设置容器的启动时间
  • 设置活跃状态为true
  • 设置关闭状态为false
  • 获取Environment对象,并加载当前系统的环境到Environment中
  • 准备监听器和事件的集合对象,默认为空
	protected void prepareRefresh() {
		// Switch to active.
		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());
			}
		}

		// Initialize any placeholder property sources in the context environment.
        // 给子类进行扩展
		initPropertySources();

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

		// Store pre-refresh 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<>();
	}
public interface ConfigurablePropertyResolver extends PropertyResolver {中的方法
  • setRequiredProperties
  • validateRequiredProperties对setRequiredProperties的属性进行验证

作用:对系统参数进行验证,比如-D ab=ba,需要ab这个属性,那么久可以进行扩展

扩展点:

public class MyApplicationContext extends ClassPathXmlApplicationContext {
    public MyApplicationContext(String... configLocations) {
        super(configLocations);
    }

    // 这里就要求了必须要有这个属性
    @Override
    protected void initPropertySources() {
        getEnvironment().setRequiredProperties("OS");
    }
}

validateRequiredProperties代码逻辑

代码逻辑是收集所有的异常信息,然后统一返回:MissingRequiredPropertiesException这个类的设计可以借鉴

	@Override
	public void validateRequiredProperties() {
		MissingRequiredPropertiesException ex = new MissingRequiredPropertiesException();
		for (String key : this.requiredProperties) {
			if (this.getProperty(key) == null) {
				ex.addMissingRequiredProperty(key);
			}
		}
		if (!ex.getMissingRequiredProperties().isEmpty()) {
			throw ex;
		}
	}

监听器和事件集合再SpringBoot启动的时候是会存在applicationListeners的,spring是不需要的,提供来扩展,SpringBoot就进行了扩展。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值