(二)Spring源码阅读:prepareRefresh方法

一、概述

prepareRefresh主要是为了容器进行刷新做准备,它实现的步骤如下:1、设置容器的启动时间。 2、设置活跃状态为true。 3、设置关闭状态为false 4、获取Environment对象,并加载当前系统的属性值到Environment对象中。5、准备监听器和事件的集合对象,默认为空的集合。

下面便是prepareRefresh方法,里面比较重要的方法是initPropertySources和validateRequiredProperties,下面我就一一介绍这些方法。

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

		// 留给子类覆盖,初始化属性资源
		initPropertySources();


		// 创建并获取环境对象,验证需要的属性文件是否都已经放入环境中
		getEnvironment().validateRequiredProperties();

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

		// 创建刷新前的监听事件集合
		this.earlyApplicationEvents = new LinkedHashSet<>();
	}

二、重要方法

(一)initPropertySources

该方法内部没有写任何东西,这个类是留给子类去拓展实现的,这个地方很能体现Spring的拓展性,下面的章节我会写对应demo进行对应的介绍。

 

(二)validateRequiredProperties

点进去 看到接口。

 再往下走,看到实现类。里面会对必填参数进行校验,如果校验不通过就会抛出异常。

	@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;
		}
	}

三、demo演示

我们以往启动spring的代码就像下面一样。

ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
Apple bean = ac.getBean(Apple.class);

我们现自己写一个 MyClassPathXmlApplicationContext 类然后继承ClassPathXmlApplicationContext 类之后重写initPropertySources方法。我们在里面设置环境变量检查的参数。

public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext {


    public MyClassPathXmlApplicationContext(String... configLocations){
        super(configLocations);
    }

    @Override
    protected void initPropertySources() {
        System.out.println("扩展initPropertySource");
        getEnvironment().setRequiredProperties("abc");
    }

}

运行,显示必要参数缺失异常。 

initPropertySources不仅可以进行参数校验还可以进行一些属性的初始化,大家可以根据实际情况使用。

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小海海不怕困难

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

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

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

打赏作者

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

抵扣说明:

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

余额充值