refresh学习

书中人 2019年08月27日 1,739次浏览
  1. 首先进入AbstractApplication中的refresh()方法中如下
public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			//上下文刷新之前的准备工作
			prepareRefresh();
		}
	}
  1. 进入prepareRefresh方法中如下代码

    1. 		// Initialize any placeholder property sources in the context environment.
      		initPropertySources();
      		// Validate that all properties marked as required are resolvable:
      		// see ConfigurablePropertyResolver#setRequiredProperties
      		getEnvironment().validateRequiredProperties();
      
  2. getEnvironment()------>createEnvironment--->new StandardEnvironment()

  3. 查看StandardEnvironment继承图如下

    1. 顶层接口为属性解析器,其中ConfigurablePropertyResolver为可配置化的属性解析器。AbstractPropertyResolver为ConfigurablePropertyResolver的抽象实现,抽象基类,用于根据任何基础源解析属性。PropertySourcesPropertyResolver是PropertyResolver的实现、根据一系列的PropertySources集合来解析属性值(所以内部持有一个PropertySources的引用)。

    2. PropertySources为PropertySource的集合、内部有很多PropertySource、相当于PropertySource集合的封装。

    3. public class MutablePropertySources implements PropertySources 
      MutablePropertySources是PropertySources的默认实现、提供了对内部的PropertySource的增删改查。
      
  4. 回到AbstractEnvironment当中、发现AbstractEnvironment持有一个propertyResolver属性解析器的引用

    1. //这里是PropertySources的实现类、用户包装PropertySource集合的封装
      private final MutablePropertySources propertySources = new MutablePropertySources();
      //AbstractEnvironment中持有propertyResolver这个属性解析器的引用
      private final ConfigurablePropertyResolver propertyResolver =new PropertySourcesPropertyResolver(this.propertySources);
      
  5. 在AbstractpropertyResolve中验证环境中必须的属性

    1. 	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;
      		}
      	}
      
  6. 初始化

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