Spring IOC容器(XML)源码解析

什么是IoC

IOC(Inversion of Control,控制反转)就是原先代码需要对对象的创建依赖交给容器去控制,我们只需要调用即可。无需关注对象的创建和销毁。IOC是一种思想而DI是实际实现。

DI(Dependency Injection,依赖注入)对象被动的绑定依赖类。对象不是主动从IOC容器寻找依赖类,而是在IOC容器实例化对象时,主动将实例化的对象与它的依赖类所绑定(注入)。
对象与对象直接的关系可通过 Xml,properties,yml 等文件去表示。

IOC容器:BeanFactory

在这里插入图片描述
BeanFactory 是顶层接口,定义了IOC容器最基础的功能 getBean(),下面有三个重要子接口:

  • ListableBeanFactory:列表化Bean工厂(Bean的集合)
  • HierarchicalBeanFactory:分层的Bean工厂,描述Bean的继承关系(Bean的关系)
  • AutowireCapableBeanFactory:自动装配规则的Bean工厂(Bean的行为)

IOC容器实现:ApplicationContext

ApplicationContext是IOC的一个高级容器,提供了附加功能:

  • 支持信息源(MessageSource
  • 资源访问(ResourcePatternResolver
  • 应用事件(ApplicationEventPublisher
    在这里插入图片描述

初始化IOC容器(XML形式)

字母替换类说明

  • A:ClassPathXmlApplicationContext
  • B:AbstractRefreshableConfigApplicationContext
  • C:AbstractApplicationContext
  • D:AbstractRefreshableApplicationContext
  • E:AbstractXmlApplicationContext
  • F:AbstractBeanDefinitionReader
  • G:XmlBeanDefinitionReader
  • H:DefaultBeanDefinitionDocumentReader
  • I:BeanDefinitionParserDelegate
  • J:BeanDefinitionReaderUtils
  • K:DefaultListableBeanFactory
A B C D E F G H I J K setConfigLocations(configLocations) [1] refresh() [2] obtainFreshBeanFactory() [3] refreshBeanFactory() [4] loadBeanDefinitions() [5] loadBeanDefinitions() [6] loadBeanDefinitions() [7] loadBeanDefinitions() [8] loadBeanDefinitions() [9] doLoadBeanDefinitions() [10] registerBeanDefinitions() [11] registerBeanDefinitions() doRegisterBeanDefinitions() [12] parseBeanDefinitions() [13] parseDefaultElement() [14] processBeanDefinition() [15] parseBeanDefinitionElement() [16] parseBeanDefinitionElement() [17] parsePropertyElements() [18] parsePropertyElements() [19] parsePropertyValue() [20] parsePropertySubElement() [21] registerBeanDefinition() [22] registerBeanDefinition() [23] A B C D E F G H I J K

步骤解析

  • [0]:初始化容器,入口为 A:ClassPathXmlApplicationContext的构造函数
  • [1]:调用父类方法设置Bean配置文件的定位路径
  • [2]:refresh() 加载Bean的配置资源。该方法是一个模板模式,定义了IOC容器启动的一个过程。通过父类C:AbstractApplicationContext 的方法来启动整个IOC容器。
    refresh() 主要是为了IOC容器Bean的生命周期管理提供条件,在创建容器前,如果有容器存在就把前容器销毁和关闭,在创建新的IOC容器。
@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// 为刷新上下文做准备,获取容器当前时间,同时设置容器同步标识
			prepareRefresh();

			// 告诉子类刷新内部bean工厂。初始化Bean工厂
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 准备bean工厂以供在此容器中使用。为BeanFactory配置容器特性,例如:类加载器,事件处理器
			prepareBeanFactory(beanFactory);

			try {
				// 允许在上下文子类中对bean工厂进行后处理。处理特殊的类:实现 BeanPostProcessor 接口
				postProcessBeanFactory(beanFactory);

				// 调用上下文中注册为 BeanPostProcessor bean的工厂处理器。
				invokeBeanFactoryPostProcessors(beanFactory);

				// 注册拦截BeanPostProcessor创建的bean处理器。
				registerBeanPostProcessors(beanFactory);

				// 为此上下文初始化消息源。
				initMessageSource();

				// 为此上下文初始化事件多播程序。
				initApplicationEventMulticaster();

				// 初始化特定上下文子类中的其他特殊bean。
				onRefresh();

				// 注册检查侦听器bean
				registerListeners();

				// 实例化所有剩余的单例Bean。
				finishBeanFactoryInitialization(beanFactory);

				// 初始化容器的生命周期事件处理器,并发布容器的生命周期事件
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// 销毁创建的Bean
				destroyBeans();

				// 取消刷新操作,重置容器的同步策略
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				
				// 重新设置公共缓存
				resetCommonCaches();
			}
		}
	}
  • [3]:创建容器,调用refreshBeanFactory() 该方法的实现为其子类AbstractRefreshableApplicationContext 实现。使用了委派模式
  • [4]:先判断 beanFactory 是否存在,如果存在则销毁bean并且关闭 beanFactory,然后创建DefaultListableBeanFactory并调用 loadBeanDefinitions() 装载Bean
@Override
	protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
		    //销毁Bean
			destroyBeans();
			//关闭工厂
			closeBeanFactory();
		}
		try {
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}
  • [5]:loadBeanDefinitions(beanFactory) 具体实现类在其子类 AbstractXmlApplicationContext当中
	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		// 创建 XmlBeanDefinitionReader,创建 Bean 读取器
	    // 并通过回调设置到容器中,容器使用该读取器读取 Bean 配置资源
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		// 为 Bean 读取器设置 Spring 资源加载器 
		// AbstractXmlApplicationContext 的抽象父类 AbstractApplicationContext 继承 DefaultResourceLoader,也就是 容器本身就是个资源管理器 
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		// 为 Bean 读取器设置 SAS xml解析器
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		// 当 Bean 读取器读取 Bean 定义的 Xml 资源文件时,启动 xml 校验机制
		initBeanDefinitionReader(beanDefinitionReader);
		// Bean 读取器真正实现的加载方法
		loadBeanDefinitions(beanDefinitionReader);
	}
  • [6]:Bean 读取器加载 Bean 配置资源
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
	    // 获取 Bean 配置资源的位置
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
		    // Xml Bean 读取器 调用父类 AbstractBeanDefinitionReader 读取定位的 Bean 配置资源
			reader.loadBeanDefinitions(configResources);
		}
		// 获取 Bean 配置资源的位置
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
		    // Xml Bean 读取器 调用父类 AbstractBeanDefinitionReader 读取定位的 Bean 配置资源
			reader.loadBeanDefinitions(configLocations);
		}
	}
  • [7]:该方法就是获取要加载的资源
	public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
	    // 获取在IOC容器初始化过程中设置的资源加载器
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
			    // 将指定的 Bean 配置信息解析为Spring IOC 容器封装的资源
			    // 加载多个指定位置的 Bean 配置信息
				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;
		}
	}
  • [8]:加载资源入口
@Override
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(new EncodedResource(resource));
	}
  • [9]:实际加载 Xml 形式 Bean 配置信息方法
	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);
		}

		Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
		if (currentResources == null) {
			currentResources = new HashSet<>(4);
			this.resourcesCurrentlyBeingLoaded.set(currentResources);
		}
		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
		try {
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
			    // 读取配置文件,转变成 I/O 流
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {
					inputSource.setEncoding(encodedResource.getEncoding());
				}
				// 具体读取方法
				return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
			}
			finally {
			    // 关闭流
				inputStream.close();
			}
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"IOException parsing XML document from " + encodedResource.getResource(), ex);
		}
		finally {
			currentResources.remove(encodedResource);
			if (currentResources.isEmpty()) {
				this.resourcesCurrentlyBeingLoaded.remove();
			}
		}
	}
  • [10]:Xml转换 DOM 对象,解析 DOM 对象
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
		    // Xml 转换 DOM
			Document doc = doLoadDocument(inputSource, resource);
			// 启动 Bean 定义解析过程
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
		
	}
  • [11]:启动 Spring IOC 容器对 Bean 定义的解析过程
	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		// 获取 BeanDefinitionDocumentReader 来对 XML 格式的 BeanDefinition 进行解析
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		// 获取 Bean 的数量
		int countBefore = getRegistry().getBeanDefinitionCount();
		// 解析过程的入口,使用委派,具体实现由 BeanDefinitionDocumentReader 进行
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		// 统计解析 Bean 的数量
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}
  • [12]:解析 DOM
protected void doRegisterBeanDefinitions(Element root) {
		// Any nested <beans> elements will cause recursion in this method. In
		// order to propagate and preserve <beans> default-* attributes correctly,
		// keep track of the current (parent) delegate, which may be null. Create
		// the new (child) delegate with a reference to the parent for fallback purposes,
		// then ultimately reset this.delegate back to its original (parent) reference.
		// this behavior emulates a stack of delegates without actually necessitating one.
		
		// 具体解析由 BeanDefinitionParserDelegate 进行
		// BeanDefinitionParserDelegate 定义了 Bean Xml 文件各种元素
		BeanDefinitionParserDelegate parent = this.delegate;
	    // 真正的解析过程
		this.delegate = createDelegate(getReaderContext(), root, parent);

		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				// We cannot use Profiles.of(...) since profile expressions are not supported
				// in XML config. See SPR-12458 for details.
				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;
				}
			}
		}
        // 解析 Bean 之前,进行自定义解析,增加解析过程的可扩展性
		preProcessXml(root);
		// 从文档根节点开始解析
		parseBeanDefinitions(root, this.delegate);
		// 解析 Bean 之后,进行自定义解析,增加解析过程的可扩展性
		postProcessXml(root);

		this.delegate = parent;
	}
  • [13]:从文档根节点开始解析
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
	    // Bean 定义的文档对象使用了 Spring 默认的 XML 命名空间
		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;
					// Bean 定义的文档元素节点使用的是Spring默认的XML 命名空间
					if (delegate.isDefaultNamespace(ele)) {
					    // 使用 Spring 的 Bean 规则解析元素节点
						parseDefaultElement(ele, delegate);
					}
					else {
					    // 如果没有使用 Sring 默认的命名空间,则使用用户自定义的解析规则
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
		    // 如果没有使用 Sring 默认的命名空间,则使用用户自定义的解析规则
			delegate.parseCustomElement(root);
		}
	}
  • [14]:使用 Spring 的 Bean 规则解析元素节点
	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		// 如果节点是 <import> 导入元素进行解析
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);
		}
		// 如果是 <alias> 别名进行解析
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
		// 普通 <bean> 进行解析
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}
  • [15]: 进行解析
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
	    // 解析 <bean> 元素
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				// 向 Spring IOC 容器注册解析得到的 Bean,这个是 Bean 定义向 IOC 容器的入口
				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));
		}
	}
  • [16]:解析 Bean 配置信息中的 元素,该方法主要处理 元素的 id、name和别名属性
	public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
		// 获取 <bean> 中的 id 属性 
		String id = ele.getAttribute(ID_ATTRIBUTE);
		// 获取 <bean> 中的 name 属性 
		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
	    // 获取 <bean> 中的 alias 属性 
		List<String> aliases = new ArrayList<>();
		// 将 <bean> 元素中所有的 name 属性值存放在别名中
		if (StringUtils.hasLength(nameAttr)) {
			String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			aliases.addAll(Arrays.asList(nameArr));
		}

		String beanName = id;
		// 如果 <bean> 元素中没有配置 id 属性,将别名中的第一个值赋给 beanName 
		if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
			beanName = aliases.remove(0);
			if (logger.isTraceEnabled()) {
				logger.trace("No XML 'id' specified - using '" + beanName +
						"' as bean name and " + aliases + " as aliases");
			}
		}
        // 检查 id 和 name 的唯一性
		if (containingBean == null) {
			checkNameUniqueness(beanName, aliases, ele);
		}
        // 详细的对 bean 进行解析
		AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
		if (beanDefinition != null) {
			if (!StringUtils.hasText(beanName)) {
				try {
					if (containingBean != null) {
					    // 如果 bean 没有配置别名、id、name,且包含了子元素则将解析的bean 使用别名进行注册
						beanName = BeanDefinitionReaderUtils.generateBeanName(
								beanDefinition, this.readerContext.getRegistry(), true);
					}
					else {
						beanName = this.readerContext.generateBeanName(beanDefinition);
						// Register an alias for the plain bean class name, if still possible,
						// if the generator returned the class name plus a suffix.
						// This is expected for Spring 1.2/2.0 backwards compatibility.
						String beanClassName = beanDefinition.getBeanClassName();
						if (beanClassName != null &&
								beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
								!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
							aliases.add(beanClassName);
						}
					}
					if (logger.isTraceEnabled()) {
						logger.trace("Neither XML 'id' nor 'name' specified - " +
								"using generated bean name [" + beanName + "]");
					}
				}
				catch (Exception ex) {
					error(ex.getMessage(), ele);
					return null;
				}
			}
			String[] aliasesArray = StringUtils.toStringArray(aliases);
			return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
		}

		return null;
	}

  • [17]:详细的对 bean 进行解析,除 id、name、alias 属性
	@Nullable
	public AbstractBeanDefinition parseBeanDefinitionElement(
			Element ele, String beanName, @Nullable BeanDefinition containingBean) {
        // 记录解析的 bean 元素
		this.parseState.push(new BeanEntry(beanName));

        // 读取 <bean> class 值
		String className = null;
		if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
		}
		// 读取 <bean> parent 值
		String parent = null;
		if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
			parent = ele.getAttribute(PARENT_ATTRIBUTE);
		}

		try {
		    // 根据 class名称和 parent 属性创建BeanDefinition
			AbstractBeanDefinition bd = createBeanDefinition(className, parent);
            // 对当前 bean 元素中设置的属性进行解析和配置,例 单例(single)属性
			parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
			// 设置描述属性
			bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
            // 对 meta 属性进行解析
			parseMetaElements(ele, bd);
			// Lookup 属性解析
			parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
			// ReplacedMethod 属性解析
			parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
            // 构造解析
			parseConstructorArgElements(ele, bd);
			// 解析 Property
			parsePropertyElements(ele, bd);
			parseQualifierElements(ele, bd);

			bd.setResource(this.readerContext.getResource());
			bd.setSource(extractSource(ele));

			return bd;
		}
		catch (ClassNotFoundException ex) {
			error("Bean class [" + className + "] not found", ele, ex);
		}
		catch (NoClassDefFoundError err) {
			error("Class that bean class [" + className + "] depends on not found", ele, err);
		}
		catch (Throwable ex) {
			error("Unexpected failure during bean definition parsing", ele, ex);
		}
		finally {
			this.parseState.pop();
		}

		return null;
	}
  • [18]:解析 元素,解析给定bean元素的属性子元素。
	public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
		NodeList nl = beanEle.getChildNodes();
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
			    // 解析<Property> 元素
				parsePropertyElement((Element) node, bd);
			}
		}
	}
  • [19]:解析 元素
	public void parsePropertyElement(Element ele, BeanDefinition bd) {
	    // 获取元素名字
		String propertyName = ele.getAttribute(NAME_ATTRIBUTE);
		if (!StringUtils.hasLength(propertyName)) {
			error("Tag 'property' must have a 'name' attribute", ele);
			return;
		}
		this.parseState.push(new PropertyEntry(propertyName));
		try {
			if (bd.getPropertyValues().contains(propertyName)) {
				error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
				return;
			}
			// 获取元素的值
			Object val = parsePropertyValue(ele, bd, propertyName);
			// 根据元素的名字和值创建实例
			PropertyValue pv = new PropertyValue(propertyName, val);
			parseMetaElements(ele, pv);
			pv.setSource(extractSource(ele));
			bd.getPropertyValues().addPropertyValue(pv);
		}
		finally {
			this.parseState.pop();
		}
	}
  • [20]:获取 元素的值,ref 封装为一个引用对象,value 封装为一个String
@Nullable
	public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
		String elementName = (propertyName != null ?
				"<property> element for property '" + propertyName + "'" :
				"<constructor-arg> element");

		// Should only have one child element: ref, value, list, etc.
		// 获取 <Property> 的子元素,只能是: ref, value, list, etc.
		NodeList nl = ele.getChildNodes();
		Element subElement = null;
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
					!nodeNameEquals(node, META_ELEMENT)) {
				// Child element is what we're looking for.
				if (subElement != null) {
					error(elementName + " must not contain more than one sub-element", ele);
				}
				else {
					subElement = (Element) node;
				}
			}
		}

        // 判断属性是ref还是 value,只能有一个
		boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
		boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
		if ((hasRefAttribute && hasValueAttribute) ||
				((hasRefAttribute || hasValueAttribute) && subElement != null)) {
			error(elementName +
					" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
		}
        // 如果是 ref,创建一个 RuntimeBeanReference 对象,里面封装的 ref
		if (hasRefAttribute) {
			String refName = ele.getAttribute(REF_ATTRIBUTE);
			if (!StringUtils.hasText(refName)) {
				error(elementName + " contains empty 'ref' attribute", ele);
			}
			RuntimeBeanReference ref = new RuntimeBeanReference(refName);
			ref.setSource(extractSource(ele));
			return ref;
		}
		 // 如果是 value,创建一个 TypedStringValue 对象,里面封装的 value
		else if (hasValueAttribute) {
			TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
			valueHolder.setSource(extractSource(ele));
			return valueHolder;
		}
		else if (subElement != null) {
		    // 解析 <Property> 子元素
			return parsePropertySubElement(subElement, bd);
		}
		else {
			// Neither child element nor "ref" or "value" attribute found.
			error(elementName + " must specify a ref or value", ele);
			return null;
		}
	}
  • [21]:解析 元素中 ref,value,集合等元素
	public Object parsePropertySubElement(Element ele, @Nullable BeanDefinition bd, @Nullable String defaultValueType) {
		// 如果 <Property> 元素没有使用 spring 默认命名空间,则使用用户自定义的规则解析内嵌元素
		if (!isDefaultNamespace(ele)) {
			return parseNestedCustomElement(ele, bd);
		}
		// 如果是 bean 则解析 bean
		else if (nodeNameEquals(ele, BEAN_ELEMENT)) {
			BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
			if (nestedBd != null) {
				nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
			}
			return nestedBd;
		}
		// 如果是 ref
		else if (nodeNameEquals(ele, REF_ELEMENT)) {
			// A generic reference to any name of any bean.
			String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
			boolean toParent = false;
			if (!StringUtils.hasLength(refName)) {
				// A reference to the id of another bean in a parent context.
				refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
				toParent = true;
				if (!StringUtils.hasLength(refName)) {
					error("'bean' or 'parent' is required for <ref> element", ele);
					return null;
				}
			}
			if (!StringUtils.hasText(refName)) {
				error("<ref> element contains empty target attribute", ele);
				return null;
			}
			RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);
			ref.setSource(extractSource(ele));
			return ref;
		}
		// <idref> 
		else if (nodeNameEquals(ele, IDREF_ELEMENT)) {
			return parseIdRefElement(ele);
		}
		// <value>
		else if (nodeNameEquals(ele, VALUE_ELEMENT)) {
			return parseValueElement(ele, defaultValueType);
		}
		// 如果是空
		else if (nodeNameEquals(ele, NULL_ELEMENT)) {
			// It's a distinguished null value. Let's wrap it in a TypedStringValue
			// object in order to preserve the source location.
			TypedStringValue nullHolder = new TypedStringValue(null);
			nullHolder.setSource(extractSource(ele));
			return nullHolder;
		}
		// 如果是 array
		else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {
			return parseArrayElement(ele, bd);
		}
		// <List>
		else if (nodeNameEquals(ele, LIST_ELEMENT)) {
			return parseListElement(ele, bd);
		}
		// <Set>
		else if (nodeNameEquals(ele, SET_ELEMENT)) {
			return parseSetElement(ele, bd);
		}
		// <Map>
		else if (nodeNameEquals(ele, MAP_ELEMENT)) {
			return parseMapElement(ele, bd);
		}
		// <props>
		else if (nodeNameEquals(ele, PROPS_ELEMENT)) {
			return parsePropsElement(ele);
		}
		else {
			error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
			return null;
		}
	}
  • [22]:将解析的 BeanDefinitionHolder 注册到 Spring IOC 容器中
	public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		// Register bean definition under primary name.
		// 获取 beanDefinition 的名称
		String beanName = definitionHolder.getBeanName();
		// 向 IOC 注册 BeanDefinition
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// Register aliases for bean name, if any.
		// 如果有别名就注册别名
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}
  • [23]:向 IOC 容器注册解析 BeanDefinition,IOC 容器初始化全部结束
/** Map of bean definition objects, keyed by bean name. */
// 存储注册信息的 beanDefinitionMap
	private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
	
		@Override
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {

		Assert.hasText(beanName, "Bean name must not be empty");
		Assert.notNull(beanDefinition, "BeanDefinition must not be null");
        // 校验解析的 BeanDefinition
		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			else if (existingDefinition.getRole() < beanDefinition.getRole()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				if (logger.isInfoEnabled()) {
					logger.info("Overriding user-defined bean definition for bean '" + beanName +
							"' with a framework-generated bean definition: replacing [" +
							existingDefinition + "] with [" + beanDefinition + "]");
				}
			}
			else if (!beanDefinition.equals(existingDefinition)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Overriding bean definition for bean '" + beanName +
							"' with an equivalent definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
		else {
			if (hasBeanCreationStarted()) {
				// Cannot modify startup-time collection elements anymore (for stable iteration)
				// 注册需要线程同步,保证数据一致性
				synchronized (this.beanDefinitionMap) {
					this.beanDefinitionMap.put(beanName, beanDefinition);
					List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					this.beanDefinitionNames = updatedDefinitions;
					removeManualSingletonName(beanName);
				}
			}
			else {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				removeManualSingletonName(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
	}

总结

Spring IOC 初始化的整个流程是 从 ClassPathXmlApplicationContext 创建实例开始,传入 Spring Bean 的配置文件地址,Spring 从开始找到这个 XML 文件,定位 XML 地址并解析成DOM 元素。Spring 将 DOM 元素转换为 Spring 自己的 Bean 对象格式 (BeanDefinition) ,内部会解析配置文件各种标签和属性,如:<Bean>,<Property>,<List>,<Set>,<Map>,ref,id,name,value等。解析完后获取到的 BeanDefinition 通过 DefaultListableBeanFactoryregisterBeanDefinition() 方法 以 bean 的名字去注册 BeanDefinition 添加到 Map 集合中。这个Map (private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256)😉 就是 Bean 的容器了。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值