一:ClassPathXmlApplicationContext

  • Post author:
  • Post category:其他


new ClassPathXmlApplicationContext(path)方法为入口,进去之后调用的为

// configLocations配置路径
// refresh 是否重新加载context,默认为true
// parent 父类context,默认加载defalutListAble
public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {
		super(parent);
		setConfigLocations(configLocations);
		if (refresh) {
			refresh();
		}
	}

之后,我们来看super(parent)方法做了什么事情。点进去一步一步追踪,最终代码如下。

看代码可以看出,如果不传parent的话,此操作并没有作用。

    // 发现super最终调用的是AbstractApplicationContext的构造方法
    public AbstractApplicationContext(@Nullable ApplicationContext parent) {
		this();
		setParent(parent);
	}

    // this()最终调用的getResourcePatternResolver方法,发现返回的是    
    // PathMatchingResourcePatternResolver这个类,这个类将AbstractApplicationContext
    // 本身当做参数传给了构造方法
    protected ResourcePatternResolver getResourcePatternResolver() {
		return new PathMatchingResourcePatternResolver(this);
	}    

    // parent为前边传进来的,默认为null
    @Override
	public void setParent(@Nullable ApplicationContext parent) {
        // 默认情况下parent为null,付完值,操作结束
		this.parent = parent;
		if (parent != null) {
            // 获取环境变量
			Environment parentEnvironment = parent.getEnvironment();
			if (parentEnvironment instanceof ConfigurableEnvironment) {
				// 合并环境变量
                getEnvironment().merge((ConfigurableEnvironment)                                     
                parentEnvironment);
			}
		}
	}

接下来我们看下setConfigLocations(configLocations);方法做了什么事情。可以看出来,该方法将配置文件转为可读格式,存储到了一个名为configLocations的数组中

    // locations为配置文件的路径
    public void setConfigLocations(@Nullable String... locations) {
		if (locations != null) {
			Assert.noNullElements(locations, "Config locations must not be null");
			// configLocations就是一数组,存储需要读取的配置文件的路径
            this.configLocations = new String[locations.length];
			for (int i = 0; i < locations.length; i++) {
                // 将路径转换为可读的格式,再存储到数组中,待之后用。
				this.configLocations[i] = resolvePath(locations[i]).trim();
			}
		}
		else {
			this.configLocations = null;
		}
	}

接下来进入到refresh()方法,请转到下篇。



版权声明:本文为Smile_ant原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。