spring源码:注册解析的BeanDefinition

一、介绍

  spring在解析xml中的bean标签时,会把该标签的所有信息封装到一个GenericBeanDefinition实例中。然后把该GenericBeanDefinition实例注册到一个beanDefinitionMap 中,供后面复杂的功能使用。

二、整体脉络

    <bean id="person" class="com.kaka.spring.beans.Person">
        <property name="age" value="22"/>
    bean>

spring对以上bean标签的处理步骤如下:

  1. 创建BeanDefinition实例
  2. 解析bean标签上的属性,并存储到BeanDefinition实例中
  3. 解析bean标签的子元素,并存储到BeanDefinition实例中
  4. 把BeanDefinition实例注册到beanDefinitionMap 中
  5. 通知监听器解析及注册完成
    本篇主要分析第4个步骤,beanDefinitionMap 的所属关系如下: spring源码:注册解析的BeanDefinition_第1张图片

三、相关类、方法

  • org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader#processBeanDefinition:解析及注册bean标签的整体过程
  • org.springframework.beans.factory.support.BeanDefinitionReaderUtils#registerBeanDefinition:注册BeanDefinition的入口
  • org.springframework.beans.factory.support.DefaultListableBeanFactory#registerBeanDefinition:根据名称注册BeanDefinition
  • org.springframework.core.SimpleAliasRegistry#registerAlias:注册BeanDefinition的别名

四、源码分析

  1. 解析及注册bean的入口,DefaultBeanDefinitionDocumentReader的processBeanDefinition()方法
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		// 1.解析bean标签,封装至BeanDefinitionHolder 
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			// 2.装饰BeanDefinitionHolder 
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// 3.注册BeanDefinition 点进去
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// 发布注册完成的事件,通知监听器
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}
  1. 使用BeanDefinitionReaderUtils工具类的registerBeanDefinition()方法注册bean
	public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		// 1.根据beanName注册BeanDefinition
		String beanName = definitionHolder.getBeanName();
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// 2.循环注册所有的bean名
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}
  1. 使用DefaultListableBeanFactory的registerBeanDefinition()方法,根据beanName注册BeanDefinition
	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");

		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				// 校验一些特殊的属性,如methodOverrides
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition oldBeanDefinition;

		oldBeanDefinition = this.beanDefinitionMap.get(beanName);
		// 该beanName对应的BeanDefinition已存在的情况
		if (oldBeanDefinition != null) {
			// 不允许覆盖,则抛出异常
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
						"': There is already [" + oldBeanDefinition + "] bound.");
			}
			else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				if (this.logger.isWarnEnabled()) {
					this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +
							"' with a framework-generated bean definition: replacing [" +
							oldBeanDefinition + "] with [" + beanDefinition + "]");
				}
			}
			else if (!beanDefinition.equals(oldBeanDefinition)) {
				if (this.logger.isInfoEnabled()) {
					this.logger.info("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + oldBeanDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (this.logger.isDebugEnabled()) {
					this.logger.debug("Overriding bean definition for bean '" + beanName +
							"' with an equivalent definition: replacing [" + oldBeanDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			// 把BeanDefinition存入beanDefinitionMap
			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;
					if (this.manualSingletonNames.contains(beanName)) {
						Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
						updatedSingletons.remove(beanName);
						this.manualSingletonNames = updatedSingletons;
					}
				}
			}
			else {
				// 把BeanDefinition存入beanDefinitionMap
				this.beanDefinitionMap.put(beanName, beanDefinition);
				// 记录beanName
				this.beanDefinitionNames.add(beanName);
				this.manualSingletonNames.remove(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (oldBeanDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
	}
  1. 使用SimpleAliasRegistry的registerAlias()方法来注册别名
	public void registerAlias(String name, String alias) {
		Assert.hasText(name, "'name' must not be empty");
		Assert.hasText(alias, "'alias' must not be empty");
		synchronized (this.aliasMap) {
			// 如果beanName与alias相同的话,删除该alias(所以当beanName与其他bean的别名重复时,会覆盖其他bean的别名)
			if (alias.equals(name)) {
				this.aliasMap.remove(alias);
				if (logger.isDebugEnabled()) {
					logger.debug("Alias definition '" + alias + "' ignored since it points to same name");
				}
			}
			else {
				String registeredName = this.aliasMap.get(alias);
				// 该别名已存在的情况
				if (registeredName != null) {
					// 该别名已经指向这个beanName了,正常返回
					if (registeredName.equals(name)) {
						// An existing alias - no need to re-register
						return;
					}
					// 不允许覆盖别名,则抛出异常
					if (!allowAliasOverriding()) {
						throw new IllegalStateException("Cannot define alias '" + alias + "' for name '" +
								name + "': It is already registered for name '" + registeredName + "'.");
					}
					if (this.logger.isInfoEnabled()) {
						logger.info("Overriding alias '" + alias + "' definition for registered name '" +
								registeredName + "' with new target name '" + name + "'");
					}
				}
				// 当存在A->B时,若再次出现A->C->B的时候则会抛出异常
				checkForAliasCircle(name, alias);
				this.aliasMap.put(alias, name);
				if (logger.isDebugEnabled()) {
					logger.debug("Alias definition '" + alias + "' registered for name '" + name + "'");
				}
			}
		}
	}

五、总结

  1. 解析bean标签的整体过程为DefaultBeanDefinitionDocumentReader的processBeanDefinition()方法
  2. 其中注册bean的工作,由BeanDefinitionReaderUtils工具类的registerBeanDefinition()方法处理
  3. 注册BeanDefinition包含两部分:根据beanName注册BeanDefinition、注册别名
  4. 根据beanName注册BeanDefinition:使用DefaultListableBeanFactory的registerBeanDefinition()方法
  5. 注册别名:使用SimpleAliasRegistry的registerAlias()方法

你可能感兴趣的:(spring源码)