源码入口

//基于xml方式进行源码分析 
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
    //设置父级容器,这里是null
        super(parent);
    //指定xml配置文件路径 这里是在项目的classpath路径下  
    //这里基于classpath配置文件进行源码分析
        this.setConfigLocations(configLocations);
        if (refresh) {
            //刷新容器 开始加载初始化容器,以及初始化,实例化Bean
            this.refresh();
        }
    }
//也可以基于注解方式进行源码分析
ApplicationContext context = new AnnotationConfigApplicationContext("com.lizhihuan.springstudy");
//在这里我们以xml方式进行源码分析

调用父级构造方法

//调用路径
1,ClassPathXmlApplicationContext.super(parent);
2,AbstractXmlApplicationContext.super(parent);
3,AbstractRefreshableConfigApplicationContext.super(parent);
4,AbstractRefreshableApplicationContext.super(parent);
5,public AbstractApplicationContext(@Nullable ApplicationContext parent) {
        this();
        this.setParent(parent);
    }
6,public AbstractApplicationContext() {
        this.logger = LogFactory.getLog(this.getClass());
        // 设置容器唯一标识
        this.id = ObjectUtils.identityToString(this);
        this.displayName = ObjectUtils.identityToString(this);
    	//实例化bean工厂后置处理器集合
        this.beanFactoryPostProcessors = new ArrayList();
    	//实例化active
        this.active = new AtomicBoolean();
    	//实例化closed
        this.closed = new AtomicBoolean();
    	//实例化 startupShutdownMonitor 同步器锁
        this.startupShutdownMonitor = new Object();
        this.applicationStartup = ApplicationStartup.DEFAULT;
    	//实例化 监听器集合
        this.applicationListeners = new LinkedHashSet();
    	//实例化 资源解析器
        this.resourcePatternResolver = this.getResourcePatternResolver();
    }
7,public void setParent(@Nullable ApplicationContext parent) {
        this.parent = parent;//设置父级容器 这未null
        if (parent != null) {
            Environment parentEnvironment = parent.getEnvironment();
            if (parentEnvironment instanceof ConfigurableEnvironment) {
               //如果父级容器不为null 则获取父级容器的Enviroment,与当前日期的Enviroment进行合并
               this.getEnvironment().merge((ConfigurableEnvironment)parentEnvironment);
            }
        }
    }

解析配置文件路径

//AbstractRefreshableConfigApplicationContext
public void setConfigLocations(@Nullable String... locations) {
        if (locations != null) {
            Assert.noNullElements(locations, "Config locations must not be null");
            this.configLocations = new String[locations.length];
            //配置文件名称可能是这样 spring-${username}.xml 所以需要解析
            for(int i = 0; i < locations.length; ++i) {
                this.configLocations[i] = this.resolvePath(locations[i]).trim();
            }
        } else {
            this.configLocations = null;
        }
    }

protected String resolvePath(String path) {
        return this.getEnvironment().resolveRequiredPlaceholders(path);
    }
//AbstractPropertyResolver
 public String resolveRequiredPlaceholders(String text) throws IllegalArgumentException {
        if (this.strictHelper == null) {
            this.strictHelper = this.createPlaceholderHelper(false);
        }

        return this.doResolvePlaceholders(text, this.strictHelper);
    }
private String doResolvePlaceholders(String text, PropertyPlaceholderHelper helper) {
        return helper.replacePlaceholders(text, this::getPropertyAsRawString);
    }
//PropertyPlaceholderHelper
public String replacePlaceholders(String value, PropertyPlaceholderHelper.PlaceholderResolver placeholderResolver) {
        Assert.notNull(value, "'value' must not be null");
        return this.parseStringValue(value, placeholderResolver, (Set)null);
    }
//递归调用  value 可能是 spring-${username${name}}.xml 
protected String parseStringValue(String value, PropertyPlaceholderHelper.PlaceholderResolver placeholderResolver, @Nullable Set<String> visitedPlaceholders) {
    //假如value 是 spring-${username}.xml
    //获取前缀${index
        int startIndex = value.indexOf(this.placeholderPrefix);
        if (startIndex == -1) {
            return value;
        } else {
            StringBuilder result = new StringBuilder(value);
		  //这里面根据占位符获取值 则是从 Enveiroment 中获取
            while(startIndex != -1) {
                //获取后缀}index
                int endIndex = this.findPlaceholderEndIndex(result, startIndex);
                if (endIndex != -1) {
                    //placeholder 是 username
                    String placeholder = result.substring(startIndex + this.placeholderPrefix.length(), endIndex);
                    String originalPlaceholder = placeholder;
                    if (visitedPlaceholders == null) {
                        visitedPlaceholders = new HashSet(4);
                    }

                    if (!((Set)visitedPlaceholders).add(placeholder)) {
                        throw new IllegalArgumentException("Circular placeholder reference '" + placeholder + "' in property definitions");
                    }
				//如果placeholder中还存在${} 这种占位符 则需要继续解析处理 递归调用当前方法
                    placeholder = this.parseStringValue(placeholder, placeholderResolver, (Set)visitedPlaceholders);
                    //proVal 是 获取到值
                    String propVal = placeholderResolver.resolvePlaceholder(placeholder);
                    if (propVal == null && this.valueSeparator != null) {
                        //如果没有获取到值,则从placeholder判断是否有容器指定的分隔符
                        int separatorIndex = placeholder.indexOf(this.valueSeparator);
                        if (separatorIndex != -1) {
                            //存在
                            String actualPlaceholder = placeholder.substring(0, separatorIndex);
                            //则获取值
                            String defaultValue = placeholder.substring(separatorIndex + this.valueSeparator.length());
                            //再次根据actualPlaceholder 进行获取值
                            propVal = placeholderResolver.resolvePlaceholder(actualPlaceholder);
                            if (propVal == null) {
                                propVal = defaultValue;
                            }
                        }
                    }

                    //获取到值之后
                    if (propVal != null) {
                        //则再次递归调用本方法
                        propVal = this.parseStringValue(propVal, placeholderResolver, (Set)visitedPlaceholders);
                        //替换值
                        result.replace(startIndex, endIndex + this.placeholderSuffix.length(), propVal);
                        if (logger.isTraceEnabled()) {
                            logger.trace("Resolved placeholder '" + placeholder + "'");
                        }

                        startIndex = result.indexOf(this.placeholderPrefix, startIndex + propVal.length());
                    } else {
                        if (!this.ignoreUnresolvablePlaceholders) {
                            throw new IllegalArgumentException("Could not resolve placeholder '" + placeholder + "' in value \"" + value + "\"");
                        }

                        startIndex = result.indexOf(this.placeholderPrefix, endIndex + this.placeholderSuffix.length());
                    }

                    ((Set)visitedPlaceholders).remove(originalPlaceholder);
                } else {
                    startIndex = -1;
                }
            }
            return result.toString();
        }
    }

刷新容器,调用refresh()方法

//AbstractApplicationContext
public void refresh() throws BeansException, IllegalStateException {
    // 同步监视器 startupShutdownMonitor  实例化和销毁容器 必须要保证同步
        synchronized(this.startupShutdownMonitor) {
            StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
            //准备刷新容器,做一些前置工作
            this.prepareRefresh();
            //实例化beanFactory 并且加载,解析配置文件,将配置文件中的中Bean 解析成为 BeanDefinition对象
            //beanFactory DefaultListableBeanFactory
            ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
            //准备BeanFacotry 通过set方法设置一些前置属性值
            this.prepareBeanFactory(beanFactory);
            try {
                //注册BeanFactory后置处理器到容器中
                this.postProcessBeanFactory(beanFactory);
                StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
                //执行容器中的BeanFactory后置处理器
                this.invokeBeanFactoryPostProcessors(beanFactory);
                //注册Bean后置处理器到容器中
                this.registerBeanPostProcessors(beanFactory);
                beanPostProcess.end();
                //初始化消息源
                this.initMessageSource();
                //初始化事件多播器
                this.initApplicationEventMulticaster();
                //刷新容器
                this.onRefresh();
                //注册监听器到容器中
                this.registerListeners();
                //执行BeanFactoryy初始化方法
                this.finishBeanFactoryInitialization(beanFactory);
                //完成容器的刷新,初始化,实例化完成
                this.finishRefresh();
            } catch (BeansException var10) {
                if (this.logger.isWarnEnabled()) {
                    this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var10);
                }
                //销毁容器中的bean
                this.destroyBeans();
                //取消容器的刷新,创建
                this.cancelRefresh(var10);
                throw var10;
            } finally {
                //重置缓存
                this.resetCommonCaches();
                contextRefresh.end();
            }
        }
    }

调用prepareRefresh()方法,准备一些前置工作

//AbstractApplicationContext
protected void prepareRefresh() {
       //记录一下刷新容器开始时间
        this.startupDate = System.currentTimeMillis();
    	//将当前容器关闭状态设置为false
        this.closed.set(false);
  		//将当前容器活跃状态设置为true
        this.active.set(true);
        if (this.logger.isDebugEnabled()) {
            if (this.logger.isTraceEnabled()) {
                this.logger.trace("Refreshing " + this);
            } else {
                this.logger.debug("Refreshing " + this.getDisplayName());
            }
        }

    	//加载Enviroment,包含一些系统环境变量,Spring中会加载两中类型的变量(systemEnvironment,systemProperties),到SpringMVC会增加三种(servletConfigInitParams,servletContextInitParams,jndiProperties)
        this.initPropertySources();
    	//校验一些变量必须存在,否则抛出异常
        this.getEnvironment().validateRequiredProperties();
        //实例化前置监听器集合  这里加this.earlyApplicationListeners == null,这个判断是因为SpringMVC容器中会存在(applicationListeners)一些监听器,需要加入到earlyApplicationListeners中 ,在当前这里个源码流程里面是不需要加这个判断的,只是为了兼容
        if (this.earlyApplicationListeners == null) {
            this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners);
        } else {
            this.applicationListeners.clear();
            this.applicationListeners.addAll(this.earlyApplicationListeners);
        }
		//实例化 前置事件发布集合
        this.earlyApplicationEvents = new LinkedHashSet();
    }

调用obtainFreshBeanFactory()方法,实例化BeanFactory

//AbstractApplicationContext
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        this.refreshBeanFactory();
        return this.getBeanFactory();
    }
//AbstractRefreshableApplicationContext
protected final void refreshBeanFactory() throws BeansException {
    	//如果之前已存在BeanFactory 则销毁Bean,关闭BeanFactory
        if (this.hasBeanFactory()) {
            this.destroyBeans();
            this.closeBeanFactory();
        }

        try {
            //实例化BeanFactory
            DefaultListableBeanFactory beanFactory = this.createBeanFactory();
            //设置BeanFactory序列化唯一标识
            beanFactory.setSerializationId(this.getId());
            //BeanFactory定制化处理
            this.customizeBeanFactory(beanFactory);
            //加载xml配置文件
            this.loadBeanDefinitions(beanFactory);
            this.beanFactory = beanFactory;
        } catch (IOException var2) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + this.getDisplayName(), var2);
        }
    }
protected void customizeBeanFactory(DefaultListableBeanFactory beanFactory) {
    //是否允许BeanDefinition被覆盖,比如 同名覆盖 默认为true
    if (this.allowBeanDefinitionOverriding != null) {
            beanFactory.setAllowBeanDefinitionOverriding(this.allowBeanDefinitionOverriding);
        }
		//是否允许存在循环依赖,默认true
        if (this.allowCircularReferences != null) {
            beanFactory.setAllowCircularReferences(this.allowCircularReferences);
        }
    }

调用loadBeanDefinitions()方法,处理基础设施

//AbstractXmlApplicationContext
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// 创建一个Xml解析器,并设置到beanFactory中
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// 设置系统环境变量,资源加载器,实体解析器
   beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// 设置是否校验xml文档格式
		initBeanDefinitionReader(beanDefinitionReader);
    	//解析xml,并完成向beanFactory中注册bean
		loadBeanDefinitions(beanDefinitionReader);
	}
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
    //会进入下面的if判断
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			reader.loadBeanDefinitions(configLocations);
		}
	}

调用loadBeanDefinitions()方法,层次调用,方法重载

//AbstractBeanDefinitionReader
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
		Assert.notNull(locations, "Location array must not be null");
		int count = 0;
		for (String location : locations) {
			count += loadBeanDefinitions(location);
		}
		return count;
	}
public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(location, null);
	}
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
    //这里的resourceLoader 就是ClassPathXmlApplication
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
		}
//因为ClassPathXmlApplication实现了ResourcePatternResolver ,所以会进入下面的if判断
		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				int count = loadBeanDefinitions(resources);
				if (actualResources != null) {
					Collections.addAll(actualResources, resources);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
				}
				return count;
			}
			catch (IOException ex) {
				throw new BeanDefinitionStoreException(
						"Could not resolve bean definition resource pattern [" + location + "]", ex);
			}
		}
		else {
			// Can only load single resources by absolute URL.
			Resource resource = resourceLoader.getResource(location);
			int count = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
			}
			return count;
		}
	}
public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		Assert.notNull(resources, "Resource array must not be null");
		int count = 0;
		for (Resource resource : resources) {
			count += loadBeanDefinitions(resource);
		}
		return count;
	}

调用loadBeanDefinitions方法(),方法重载

//XmlBeanDefinitionReader
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
    //将resource进行编码处理
		return loadBeanDefinitions(new EncodedResource(resource));
	}
public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		Assert.notNull(encodedResource, "EncodedResource must not be null");
		if (logger.isTraceEnabled()) {
			logger.trace("Loading XML bean definitions from " + encodedResource);
		}
//当前是否已经存在encodedResource  这个资源,如果存在则报错
		Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();

		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
//将resource 转成inputStream,然后包装成inputSource
		try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
                //设置编码格式
				inputSource.setEncoding(encodedResource.getEncoding());
			}
            //开始解析xml文件,并将bean注册到IOC容器中
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"IOException parsing XML document from " + encodedResource.getResource(), ex);
		}
		finally {
            //最后从本地线程中移除当前资源
			currentResources.remove(encodedResource);
			if (currentResources.isEmpty()) {
				this.resourcesCurrentlyBeingLoaded.remove();
			}
		}
	}

调用doLoadBeanDefinitions()方法

//XmlBeanDefinitionReader
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
            //将xml配置文件解析成Document对象
			Document doc = doLoadDocument(inputSource, resource);
            //将Document对象解析成BeanDefinition,同时将beanDefinition对象注册到IOC容器中
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
		catch (BeanDefinitionStoreException ex) {
			throw ex;
		}
		catch (SAXParseException ex) {
			throw new XmlBeanDefinitionStoreException(resource.getDescription(),
					"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
		}
		catch (SAXException ex) {
			throw new XmlBeanDefinitionStoreException(resource.getDescription(),
					"XML document from " + resource + " is invalid", ex);
		}
		catch (ParserConfigurationException ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"Parser configuration exception parsing XML from " + resource, ex);
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"IOException parsing XML document from " + resource, ex);
		}
		catch (Throwable ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"Unexpected exception parsing XML document from " + resource, ex);
		}
	}
	protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
		return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
				getValidationModeForResource(resource), isNamespaceAware());
	}
//使用那种方式校验xml配置文件
protected int getValidationModeForResource(Resource resource) {
		int validationModeToUse = getValidationMode();
		if (validationModeToUse != VALIDATION_AUTO) {
			return validationModeToUse;
		}
		int detectedMode = detectValidationMode(resource);
		if (detectedMode != VALIDATION_AUTO) {
			return detectedMode;
		}
		// Hmm, we didn't get a clear indication... Let's assume XSD,
		// since apparently no DTD declaration has been found up until
		// detection stopped (before finding the document's root tag).
		return VALIDATION_XSD;
	}

调用registerBeanDefinitions()方法

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
    //创建Document转换BeanDefinition解析器
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
    //获取IOC容器中已有的bean数量
		int countBefore = getRegistry().getBeanDefinitionCount();
    //解析,注册
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

调用registerBeanDefinitions()方法,将Document转换成BeanDefinition

//DefaultBeanDefinitionDocumentReader
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}
protected void doRegisterBeanDefinitions(Element root) {
		//实际解析xml种各种标签的对象 解析类
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);
//校验XML默认的命名空间
    //默认命名空间是 Spring 的核心命名空间,用于解析和处理 Spring 配置文件中的 bean 定义和其他配置元素。
		if (this.delegate.isDefaultNamespace(root)) {
            //获取profile 是否指定使用那种环境下的配置文件
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}
//解析xml前置处理 需要子类实现
		preProcessXml(root);
		parseBeanDefinitions(root, this.delegate);
    //解析xml后置处理 需要子类实现
		postProcessXml(root);

		this.delegate = parent;
	}

调用parseBeanDefinitions()方法

//DefaultBeanDefinitionDocumentReader
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
    //xml默认命名空间
    //即 http://www.springframework.org/schema/beans
		if (delegate.isDefaultNamespace(root)) {
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
                        //处理默认标签 bean beans import alias
						parseDefaultElement(ele, delegate);
					}
					else {
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			delegate.parseCustomElement(root);
		}
	}

调用parseDefaultElement()解析默认标签

private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
            //import
			importBeanDefinitionResource(ele);
		}
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {//alias
			processAliasRegistration(ele);
		}
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {//bean
			processBeanDefinition(ele, delegate);
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// beans
			doRegisterBeanDefinitions(ele);
		}
	}

调用processBeanDefinition()方法,解析bean标签

protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
    //BeanDefinition的包装类(bean beanName,aliases)
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// Send registration event.
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}

更多推荐