SpringIOC源码解析

           Spring源码从头看起

           -----------------------------------------------------------------      

      一.概括

          在用SpringIOC的时候,我们将要创建对象和管理对象关系的功能交给了SpringIOC,让它来帮我们完成,我们只需要拿到IOC容器,再通过IOC容器提供的getBean(BeanName)来获取对象就可以了。我们在调用IOC容器之前,会将Bean的信息写在一个配置文件里面,让IOC容器读取配置文件,根据配置文件创建Bean。IOC的源码讲的主要是将配置文件变成可以读取的资源,然后解析配置文件的离得内容,将配置文件中的bean转化为IOC容器能够懂的内部数据结构。

          在介绍SpringIOC源码的时候先要介绍几个重要的人物
          1.接口BeanFactory,最核心最基本的IOC容器,它规范了具体IOC容器的实现,对外提供了获取Bean的方法。具体实现比如XmlBeanFactory
          2.接口Resource,资源的最初始接口,Resource接口抽象了所有Spring内部使用到的底层资源:File、URL、Classpath等。

          在Java中,将不同来源的资源抽象成URL,通过注册不同的handler(URLStreamHandler)来处理不同来源间的资源读取逻辑。而URL中却没有提供一些基本方法来实现自己的抽象结构。因而Spring对其内部资源,使用了自己的抽象结构:Resource接口来封装。    

          3. BeanDefinitionRegistry,其实bean是注册在它这的,SpringIOC将BeanName和BeanDefinition以键值对的形式存储在BeanDefinitionRegistry的map属性中,又DefaultListableBeanFactory即实现了BeanFactory又实现了BeanDefinitionRegistry,所以说bean是放在IOC容器中的,从这里可以看出BeanFactory接口其实只提供了对外获取Bean的方法,没有提供注册bean的方法。

          4.XmlBeanDefitionReader,负责读取资源文件,将资源文件变成输入流,解析输入流,将配置文件的内容封装成一个Document,读取Document,注册bean。在XmlBeanDefitionReader中主要做的就是将资源文件变成输入流,后面的功能是调用其他的类来实现的。

          5.DefaultDocumentLoader,解析输入流,将配置文件的内容封装成一个Document。

          6.DefaultBeanDefinitionDocumentReader,拿到Document后从Document的根节点开始一个个解析bean,并调BeanDefinitionReaderUtils注册bean。这里的解析只是一个很粗略的解析。

          7.BeanDefinitionParserDelegate,负责对一个bean里面的属性和元素进行具体的解析,即将xml中的Element元素解析完成后封装成BeanDefinition。

          8.DefaultListableBeanFactory继承了BeanDefinitionRegistry,将BeanDefinition封装交给DefaultListableBeanFactory封装。


      二.源码介绍

          SpringIOC配置文件         

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
                     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
                     http://www.springframework.org/schema/context
                     http://www.springframework.org/schema/context/spring-context-3.0.xsd
                     http://www.springframework.org/schema/aop
                     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
                     http://www.springframework.org/schema/tx
                     http://www.springframework.org/schema/tx/spring-tx-3.0.xsd">

	<bean id="student" class="com.spring.bean.Student">
		<property name="name" value="zhangsan" />
	</bean>

	<bean name="school" class="com.spring.bean.School">
	</bean>

	<bean id="factoryBeanPojo" class="com.spring.bean.FactoryBeanPojo">
		<property name="type" value="student" />
	</bean>
</beans>  

         测试Java代码        

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

import com.spring.bean.Student;

public class SpringTest {
	public static void main(String[] args){
		String url = "com/spring/config/BeanConfig.xml";
		/*ClassPathXmlApplicationContext cpxa = new ClassPathXmlApplicationContext(url);
		Student student = (Student) cpxa.getBean("student");*/
		
		ClassPathResource resource = new ClassPathResource(url);
		DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
		XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
		reader.loadBeanDefinitions(resource);
		Student student = (Student) factory.getBean("student");
		System.out.println("test:******"+student.getName());
		BeanFactory beanFactory = new XmlBeanFactory(resource); 
	}

}

XmlBeanDefinitionReader

封装资源文件。当进入XmlBeanDefinitionReader后首先对参数Resource使用EncodedResource类进行封装,获取输入流。从Resource中获取对应的InputStream并构造InputSource。通过构造的InputSource实例和Resource实例继续调用函数doLoadBeanDefinitions。

public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
	        //将Resource转变为EncodedResource,EncodedResource主要是对加载的资源进行编码处理
		//当设置了编码属性时Spring会使用相应的编码作为输入流的编码
		return loadBeanDefinitions(new EncodedResource(resource));
}

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		Assert.notNull(encodedResource, "EncodedResource must not be null");
		if (logger.isInfoEnabled()) {
			logger.info("Loading XML bean definitions from " + encodedResource.getResource());
		}
                //加载已有的资源文件
		Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
		if (currentResources == null) {
			currentResources = new HashSet<EncodedResource>(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 {
				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();
			}
		}
	}


前面可以看成是准备工作,doLoadBeanDefinitions(InputSource inputSource, Resource resource)方法可以看成是解析XML文件获取相应的BeanDefinition,并将数据结构注册给IOC容器的蓝图方法,因为在这个方法里面主要做了三步:1.获取配置文件的验证模式;2.根据验证模式,解析XML获取对应的Document元素;3.解析Document元素,将解析出来的内容封装成IOC容器想要的数据结构并注册到IOC容器中。而重点工作在第三步,但第三步却不在XmlBeanDefinitionReader中完成

    /**
      * 获取对XML文件的验证模式
      * 加载XML文件并解析,并得到XML对应的Document
      * 根据返回的Document注册Bean信息
      */
	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {
		try {
			//获取XML的验证模式
			int validationMode = getValidationModeForResource(resource);
			//解析XML文件,获取XML文件对应的Document
			Document doc = this.documentLoader.loadDocument(
					inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
			//解析Document,将里面对应的bean转变成BeanDefinition并注册到BeanFactory
			return registerBeanDefinitions(doc, resource);
		}
		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);
		}
	}

 //解析Document,将里面的内容封装成一个个BeanDefinition并且注册给IOC容器
	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		// Read document based on new BeanDefinitionDocumentReader SPI.
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		int countBefore = getRegistry().getBeanDefinitionCount();
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}


获取Resource的验证模式,Spring用来检测验证模式的方法是判断是否包含DOCTYPE,若包含就是DTD,否则就是XSD。

       //获取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;
		}
		return VALIDATION_XSD;
	}

	protected int detectValidationMode(Resource resource) {
		if (resource.isOpen()) {
			throw new BeanDefinitionStoreException(
					"Passed-in Resource [" + resource + "] contains an open stream: " +
					"cannot determine validation mode automatically. Either pass in a Resource " +
					"that is able to create fresh streams, or explicitly specify the validationMode " +
					"on your XmlBeanDefinitionReader instance.");
		}

		InputStream inputStream;
		try {
			inputStream = resource.getInputStream();
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"Unable to determine validation mode for [" + resource + "]: cannot open InputStream. " +
					"Did you attempt to load directly from a SAX InputSource without specifying the " +
					"validationMode on your XmlBeanDefinitionReader instance?", ex);
		}

		try {
			//把自动检测验证模式的工作委托给专门处理类 XmlValidationModeDetector 
			return this.validationModeDetector.detectValidationMode(inputStream);
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException("Unable to determine validation mode for [" +
					resource + "]: an error occurred whilst reading from the InputStream.", ex);
		}
	}

	

        /**
	  *何为EntityResolver?官网解释: 
	  *若SAX应用程序需要实现自定义处理外部实体,必须实现此接口并用 setEntityResolver方法向SAX驱动器注册一个实例。默认的寻找规则,即通过网络(实现上就是声明的DTD的URI地址)来下载相应的DTD声明并进行验证。 
	  *对于解析一个XML,SAX首先读取该XML文档上的声明,根据声明去寻找相应的DTD定义,以便对文档进行一个验证。
	  *下载过程漫长,且当网络中断或者不可用时会报错,就是因为相应的DTD声明没有被找到的原因。
	  *EntityResolver作用是项目本身就能提供一个如何寻找DTD声明的方法,也就是由程序来实现寻找DTD声明的过程,比如我们将DTD文件放到项目中某处,在实现的时候直接将此文档读取并返回给SAX即可,
	  *这样就避免通过网络来寻找对应的声明。 先看看entityResolver接口方法声明: 
	  */
	protected EntityResolver getEntityResolver() {
		if (this.entityResolver == null) {
			// 获取默认的ResourceLoader
			ResourceLoader resourceLoader = getResourceLoader();
			if (resourceLoader != null) {
				this.entityResolver = new ResourceEntityResolver(resourceLoader);
			}
			else {
				this.entityResolver = new DelegatingEntityResolver(getBeanClassLoader());
			}
		}
		return this.entityResolver;
	}
到此在XmlBeanDefinitionReader类中的工作基本完成了,XmlBeanDefinitionReader做出了向IOC容器注册bean的基本步骤,解析XML文件为Document元素,解析Document元素注册bean,但这两步具体的实现都不是在XmlBeanDefinitionReader中完成的。XmlBeanDefinitionReader具体做的是将Resource转变为输入流,获取配置文件的验证模式,为将配置文件解析为Document做准备。由此可以看出XmlBeanDefinitionReader做的都是一些准备工作。


DefaultDocumentLoader

//通过SAX解析XML文档的套路大致差不多,同样首先创建DocumentBuilderFactory,再通过DocumentBuilderFactory创建DocumentBuilder,进而解析inputSource来返回Document对象
	public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
			ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {

		DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
		if (logger.isDebugEnabled()) {
			logger.debug("Using JAXP provider [" + factory.getClass().getName() + "]");
		}
		DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
		//就像平时解析一个xml文件一样,返回XML文件对应的Document
		return builder.parse(inputSource);
	}

DefaultBeanDefinitionDocumentReader

DefaultBeanDefinitionDocumentReader解析Document元素,它可以看成是一种粗粒度的解析,解析在配置文化中与Bean同级的节点,而对Bean的属性和子节点交由BeanDefinitionParserDelegate去解析

public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;

		logger.debug("Loading bean definitions");
		Element root = doc.getDocumentElement();//获取根节点

		BeanDefinitionParserDelegate delegate = createHelper(readerContext, root);
        //空方法,为子类设计,留待扩展,在解析Document之前进行预处理
		preProcessXml(root);
		//从Document的根元素开始进行Bean定义的Document对象
		parseBeanDefinitions(root, delegate);
		//空方法,为子类设计,留待扩展,在解析Document之前进行预处理
		postProcessXml(root);
	}

    //开始解析Element了,并注册BeanDefinition
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		//判断是否默认命名空间还是自定义命名空间,
		//与Spring中固定的命名空间 http://www.Springframework.org/schema/beans 进行比对,
		//若一致则认为是Spring默认标签,否则就认为是自定义标签
		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)) {
						//解析Spring自带的标签
						parseDefaultElement(ele, delegate);
					}
					else {
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			// 解析自定义元素节点 
			delegate.parseCustomElement(root);
		}
	}

	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);//解析import元素
		}
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);//解析alias元素
		}
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);//解析bean元素
		}
	}

    //将配置文件中的bean解析成Spring中的内部数据结构BeanDefinition,BeanDefinitionParserDelegate BeanDefinition的代理解析器
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		//对bean的属性和里面的子元素进行具体解析
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			//查看元素中是否有自定义的标签
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// 将已经解析好了的BeanDefinition封装到Beanfactory中
				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));
		}
	}

BeanDefinitionParserDelegate

BeanDefinitionParserDelegate负责对Bean节点的具体解析,解析Bean节点的属性和子节点,并将解析好了的属性设入到BeanDefinitionHolder这个Spring所定义的数据结构中去,BeanDefinitionHolder是BeanDefinition的一个封装类,里面含有BeanDefinition元素

public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
		return parseBeanDefinitionElement(ele, null);
	}

	public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
		String id = ele.getAttribute(ID_ATTRIBUTE);
		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);

		List<String> aliases = new ArrayList<String>();
		if (StringUtils.hasLength(nameAttr)) {
			String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, BEAN_NAME_DELIMITERS);
			aliases.addAll(Arrays.asList(nameArr));
		}

		String beanName = id;
		//如果没有id的话,用别名的第一个来作为名字
		if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
			beanName = aliases.remove(0);
			if (logger.isDebugEnabled()) {
				logger.debug("No XML 'id' specified - using '" + beanName +
						"' as bean name and " + aliases + " as aliases");
			}
		}

		if (containingBean == null) {
			//监测名字的唯一性
			checkNameUniqueness(beanName, aliases, ele);
		}
        //解析Element,即对bean进行详细解析
		AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
		if (beanDefinition != null) {
			if (!StringUtils.hasText(beanName)) {
				try {
					if (containingBean != null) {
						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.isDebugEnabled()) {
						logger.debug("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;
	}

	public AbstractBeanDefinition parseBeanDefinitionElement(
			Element ele, String beanName, BeanDefinition containingBean) {
        //将beanName放入一个堆中
		this.parseState.push(new BeanEntry(beanName));
        //获取bean中的class属性 
		String className = null;
		if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
		}

		try {
			//获取bean中的parent属性
			String parent = null;
			if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
				parent = ele.getAttribute(PARENT_ATTRIBUTE);
			}
			AbstractBeanDefinition bd = createBeanDefinition(className, parent);
            //解析配置文件中bean的属性
			parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
			bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
            // 对<Bean>元素的meta(元数据)、lookup-method、replaced-method等子元素进行解析
			parseMetaElements(ele, bd);
			parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
			parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
            //对<Bean>元素的构造方法进行解析
			parseConstructorArgElements(ele, bd);
			// 解析<Bean>元素的<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;
	}

具体看看BeanDefinitionParserDelegate是如何解析Bean的属性和子节点的

BeanDefinitionParserDelegate解析Bean的属性

public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
			BeanDefinition containingBean, AbstractBeanDefinition bd) {
        //判断Bean节点是否带有scope属性,如果有就放入到AbstractBeanDefinition中去
		if (ele.hasAttribute(SCOPE_ATTRIBUTE)) {
			// Spring 2.x "scope" attribute
			bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE));
			if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {
				error("Specify either 'scope' or 'singleton', not both", ele);
			}
		}
		//判断Bean节点是否带有singleton属性,如果有就放入到AbstractBeanDefinition中去
		else if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {
			// Spring 1.x "singleton" attribute
			bd.setScope(TRUE_VALUE.equals(ele.getAttribute(SINGLETON_ATTRIBUTE)) ?
					BeanDefinition.SCOPE_SINGLETON : BeanDefinition.SCOPE_PROTOTYPE);
		}
		else if (containingBean != null) {
			// Take default from containing bean in case of an inner bean definition.
			bd.setScope(containingBean.getScope());
		}
       
		if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) {
			bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE)));
		}
        //判断Bean节点是否带有lazy-init属性,如果是默认就放false,如果不是就放true
		String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
		if (DEFAULT_VALUE.equals(lazyInit)) {
			lazyInit = this.defaults.getLazyInit();
		}
		bd.setLazyInit(TRUE_VALUE.equals(lazyInit));
        //判断Bean节点是否带有autowire属性,如果有就放入到AbstractBeanDefinition中去
		String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
		bd.setAutowireMode(getAutowireMode(autowire));
         //判断Bean节点是否带有dependency-check属性,如果有就放入到AbstractBeanDefinition中去
		String dependencyCheck = ele.getAttribute(DEPENDENCY_CHECK_ATTRIBUTE);
		bd.setDependencyCheck(getDependencyCheck(dependencyCheck));

		if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
			String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE);
			bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, BEAN_NAME_DELIMITERS));
		}
         //判断Bean节点是否带有autowire-candidate属性,如果有就放入到AbstractBeanDefinition中去 
		String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE);
		if ("".equals(autowireCandidate) || DEFAULT_VALUE.equals(autowireCandidate)) {
			String candidatePattern = this.defaults.getAutowireCandidates();
			if (candidatePattern != null) {
				String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
				bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
			}
		}
		else {
			bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate));
		}
         //判断Bean节点是否带有primary属性,如果有就放入到AbstractBeanDefinition中去 
		if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) {
			bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE)));
		}
        //判断Bean节点是否带有init-method属性,如果有就放入到AbstractBeanDefinition中去 
		if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
			String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE);
			if (!"".equals(initMethodName)) {
				bd.setInitMethodName(initMethodName);
			}
		}
		else {
			if (this.defaults.getInitMethod() != null) {
				bd.setInitMethodName(this.defaults.getInitMethod());
				bd.setEnforceInitMethod(false);
			}
		}
        //判断Bean节点是否带有destroy-method属性,如果有就放入到AbstractBeanDefinition中去 
		if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
			String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE);
			if (!"".equals(destroyMethodName)) {
				bd.setDestroyMethodName(destroyMethodName);
			}
		}
		else {
			if (this.defaults.getDestroyMethod() != null) {
				bd.setDestroyMethodName(this.defaults.getDestroyMethod());
				bd.setEnforceDestroyMethod(false);
			}
		}
        //判断Bean节点是否带有factory-method属性,如果有就放入到AbstractBeanDefinition中去 
		if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
			bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE));
		}
		//判断Bean节点是否带有factory-bean属性,如果有就放入到AbstractBeanDefinition中去 
		if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) {
			bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE));
		}

		return bd;
	}

BeanDefinitionParserDelegate解析Bean的子节点

//对bean的子元素property进行解析
	public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
		NodeList nl = beanEle.getChildNodes();
		//遍历bean的子元素
		for (int i = 0; i < nl.getLength(); i++) {
			Node node = nl.item(i);
			if (isCandidateElement(node) && nodeNameEquals(node, PROPERTY_ELEMENT)) {
				parsePropertyElement((Element) node, bd);
			}
		}
	}


	public void parsePropertyElement(Element ele, BeanDefinition bd) {
		//获取property中对应的name
		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 {
			//如果有同名的property就直接返回,第一个起作用
			if (bd.getPropertyValues().contains(propertyName)) {
				error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
				return;
			}
			// 解析<property>元素, 返回的对象对应<property>元素的解析结果, 最终封装到PropertyValue中, 并设置到BeanDefinitionHolder中 
			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();
		}
	}

	public Object parsePropertyValue(Element ele, BeanDefinition bd, String propertyName) {
		String elementName = (propertyName != null) ?
						"<property> element for property '" + propertyName + "'" :
						"<constructor-arg> element";

		// Should only have one child element: 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;
				}
			}
		}
      
		boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);//是否在property元素中含有ref
		boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);//是否在property元素中含有value
		//不能即含有ref还含有value
		if ((hasRefAttribute && hasValueAttribute) ||
				((hasRefAttribute || hasValueAttribute) && subElement != null)) {
			error(elementName +
					" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
		}

		if (hasRefAttribute) {
			String refName = ele.getAttribute(REF_ATTRIBUTE);
			if (!StringUtils.hasText(refName)) {
				error(elementName + " contains empty 'ref' attribute", ele);
			}
			//将ref的信息封装到RuntimeBeanReference中
			RuntimeBeanReference ref = new RuntimeBeanReference(refName);
			ref.setSource(extractSource(ele));
			return ref;
		}
		else if (hasValueAttribute) {
			//将value的信息封装到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 {
			// propery元素既没有ref或value属性, 也没有子元素, 解析出错返回null  
			error(elementName + " must specify a ref or value", ele);
			return null;
		}
	}

当将一个个Bean完整的解析,返回Bean的封装数据结构BeanDefinitionHolder,回到DefaultBeanDefinitionDocumentReader,由DefaultBeanDefinitionDocumentReader调用BeanDefinitionRegistry将从BeanDefinitionHolder中取出BeanDefinition并注册到IOC容器中,在这里IOC容器指的是DefaultListableFactory

DefaultListableBeanFactory

public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

		//向IoC容器注册BeanDefinition
		String beanName = definitionHolder.getBeanName();
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// 如果有别名,也向容器注册别名
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String aliase : aliases) {
				registry.registerAlias(beanName, aliase);
			}
		}
	}

	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 {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		synchronized (this.beanDefinitionMap) {
			Object oldBeanDefinition = this.beanDefinitionMap.get(beanName);
			if (oldBeanDefinition != null) {
				if (!this.allowBeanDefinitionOverriding) {
					throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
							"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
							"': There is already [" + oldBeanDefinition + "] bound.");
				}
				else {
					if (this.logger.isInfoEnabled()) {
						this.logger.info("Overriding bean definition for bean '" + beanName +
								"': replacing [" + oldBeanDefinition + "] with [" + beanDefinition + "]");
					}
				}
			}
			else {
				this.beanDefinitionNames.add(beanName);
				this.frozenBeanDefinitionNames = null;
			}
			//将beanName和对应的beanDefinition放入到容器的map属性中
			this.beanDefinitionMap.put(beanName, beanDefinition);
            //重新设置beanDefinition
			resetBeanDefinition(beanName);
		}
	}


       三.关系图

       到此IOC源码的解析基本完成了,如果抛去SpringIOC中那些繁杂的关系,现在来看还是挺简单的,应该画一下他们之间的关系图的

图中空心三角加实线代表继承、空心三角加虚线代表实现、实线箭头加虚线代表依赖、实心菱形加实线代表组合。这里用下划线代表接口,没有下划线的代表类。但在这个图里还缺少了DefaultBeanDefinitionDocumentReader和BeanDefinitionParserDelegate的关系,DefaultBeanDefinitionDocumentReader和DefaultListableFactory的关系。

PS:刚开始看这个图的时候是一头雾水的,但将源码看了几遍后再回过头来看图还是很容易理解的。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值