1. 程式人生 > >Spring原始碼分析(二)(IoC容器的實現)(3)

Spring原始碼分析(二)(IoC容器的實現)(3)

BeanDefinition的載入和解析

    這個載入過程,相當於把定義的BeanDefinition在IoC容器中轉化成一個Spring內部表示的資料結構的過程。IoC容器對Bean的管理和依賴注入功能的實現,是通過對其持有的BeanDefinition進行各種相關操作來完成的。這些BeanDefinition資料在IoC容器中通過一個HashMap來保持和維護。當然這只是一種比較簡單的維護方式,如果需要提高IoC容器的效能和容量,完全可以自己做一些擴充套件。

    下面,從DefauItListaleBeanFactory 的設計入手,看看IoC 容器是怎樣完成BeanDefinition載入的。在開始分析之前,先回到IoC容器的初始化入口,也就是看一下refresh方法。這個方法的最初是在FileSystemXmlApplicationContext的建構函式中被呼叫的,它的呼叫標誌著容器初始化的開始,這些初始化物件就是BeanDefinition資料,初始化入口如程式碼如下:

    public FileSystemXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
            throws BeansException {

        super(parent);
        setConfigLocations(configLocations);//設定此應用程式上下文的配置位置。如果沒有設定,實現可能會在適當的時候使用預設值。
        if (refresh) {
            refresh();//AbstractApplicationContext的refresh
        }
    }

    對容器的啟動來說, refresh是一個很重要的方法,下面介紹一下它的實現。該方法在AbstractApplicationContext類(它FileSystemXmlApplicationContext的基類)中找到.它詳細地描述了整個AppIicationContext 的初始化過程,比如BeanFactory 的更新,MessageSource和PostProcessor的註冊,等等。

	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			//這裡是在子類中啟動refreshBeanFactory()的地方
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				//設定BeanFactory的後置處理
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				//呼叫BeanFactory的後置處理器,這些後置處理器是在Bean定義中向容器註冊的
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				//註冊Bean的後處理器,在Bean建立過程中呼叫
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				//對上下文的訊息源進行初始化
				initMessageSource();

				// Initialize event multicaster for this context.
				//初始化上下文中的事件機制
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				//初始化其他的特殊bean
				onRefresh();

				// Check for listener beans and register them.
				//檢查監聽Bean並且將這些Bean向容器註冊
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				//例項化所有的(non-lazy-init)單例
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				//釋出容器事件,結束Refresh過程
				finishRefresh();
			}

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

				// Destroy already created singletons to avoid dangling resources.
				//為防止Bean資源佔用在異常處理中,銷燬已經在前面過程中生成的單例bean
				destroyBeans();

				// Reset 'active' flag.
				//重置'active'標誌
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

    進入到AbstractRefreshableApplicationContext的refreshBeanFactory()方注中,在這個方法中建立了BeanFactory。在建立loC容器前,如果已經有容器存在,那麼需要把已有的容器銷燬和關閉,保證在refresh以後使用的是新建立起來的IoC容器。這麼看來,這個refresh非常像重啟動容器,就像重啟動計算機那樣。在建立好當前的IoC容器以後,開始了對容器的初始化過程,比如BeanDefinition的載入。具體互動過程如:

    首先從AbstractRefreshableApplicationContext的refreshBeanFactory開始瞭解這個Bean定義資訊載入的過程。

	protected final void refreshBeanFactory() throws BeansException {
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			//建立IoC容器,這裡用的是DefaultListableBeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			customizeBeanFactory(beanFactory);
			//啟動對Bena的載入
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

    這裡呼叫的loadBeanDefinitions實際上是一個抽象方法,它實際的載入過程發生在AbstractRefreshableApplicationContext的子類AbstractXmlApplicationContext中的實現,在這個loadBeanDefinitions中,初始化了讀取器XmlBeanDefinitionReader ,然後把這個讀取器在IoC容器中設定好(過程和程式設計式使用XmlBeanFactory是類似的),最後是啟動讀取器來完成BeanDefinition在IoC容器中的載入,如程式碼所示。

	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		//建立XmlBeanDefinitionReader並通過回撥設定到BeanFactory中去,
		// 建立BeanFactory的過程可以參考上下文對程式設計式使用IoC容器相關分析,這裡也是使用的DefaultListableBeanFactory
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		//在這裡設定XmlBeanDefinitionReader,為XmlDefinitionReader配ResourceLoader,因為DefaultResourceLoader是父類,所以this可以直接被使用
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		//這是啟動Bean定義資訊載入的過程
		initBeanDefinitionReader(beanDefinitionReader);
		loadBeanDefinitions(beanDefinitionReader);
	}

	protected Resource[] getConfigResources() {
		return null;
	}

    接著就是loadBeanDefinitions呼叫的地方,首先得到BeanDefinition資訊的Resource定位,然後直接呼叫XmlBeanDefinitionReader來讀取,具體的載入過程是委託給BeanDefinitionReader完成的。因為這裡的BeanDefinition是通過XML檔案定義的,所以這裡使用XmlBeanDefinitionReader來載入BeanDefinition到容器中,如程式碼所示。
 

	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		//以Resource的方式獲得配置檔案的資源
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
		//以String的方式獲得配置檔案的資源
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			reader.loadBeanDefinitions(configLocations);
		}
	}

    通過以上對實現原理的分析,我們可以看到,在初始化FileSystmXmlApplicationContext的過程中是通過呼叫IoC容器的refresh來啟動整個BeanDefinition的載入過程的,這個初始化是通過定義的XmlBeanDefinitionReader來完成的。同時,我們也知道實際使用的IoC容器是DefuItListabIeBeanfactory ,具體的Resource載入在XmlBeanDefinitionRcader讀入BeanDefinition時實現。因為Spring可以對應不同形式的BeanDefinition. 由於這裡使用的是XML 方式的定義,所以需要使用XmlBeanDefinitionReader 。如果使用了其他的BeanDefinition方式,就需要使用其他種類的BeanDefinitionReader來完成資料的載入工作。在XmlBeanDefinitionReader的實現中可以看到,是在reader.loadBeanDefinitions 中開始進行BeanDefinition的載入的,而這時XmlBeanDefinitionReader的父類AbstractBeanDefinitionReader已經為BeanDefinition的載入做好了準備,如程式碼所示。

	public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		//如果Resource為空則停止BeanDefinition的載入
		//然後啟動載入BeanDefinition的過程,這個過程會遍歷整個Resource集合所包含的BeanDefinition資訊
		Assert.notNull(resources, "Resource array must not be null");
		int counter = 0;
		for (Resource resource : resources) {
			counter += loadBeanDefinitions(resource);
		}
		return counter;
	}

    這裡呼叫的是loadBeanDefinitions(Resourceres)方法, 但這個方法在AbstractBeanDefinitionReader類裡是沒有實現的,它是一個介面方法,具體的實現在XmlBeanDefinitionReader中。在讀取器中,需要得到代表XML檔案的Resource ,因為這個Resource物件封裝了對XML檔案的I/O操作,所以讀取器可以在開啟I/O流後得到XML的檔案物件。有了這個檔案物件以後,就可以按照Spring的Bean定義規則來對這個XML的文件樹進行解析了.這個解析是交給BeanDefinitionParserDelegate來完成的,看起來實現脈絡很清楚。具體可以參考程式碼實現,如程式碼所示。
 

        //呼叫入口
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(new EncodedResource(resource));
	}


        //載入xml形式的BeanDefinition的地方
	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);
		}

		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 {
			//這裡得到xml檔案,並得到IO的InputSource準備進行讀取
			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方法中,這是從特定的XML檔案中實際載入BeanDefinition的地方
	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {
		try {
			//這裡取得XML檔案的Document物件,這個解析過程是由doLoadDocument完成的這個
			// doLoadDocument是DefaultDocumentLoader,在定義documentLoader的地方建立
			Document doc = doLoadDocument(inputSource, resource);
			//這裡啟動的是對BeanDefinition解析的詳細過程,這個解析會使用到Spring的Bean配置規則。
			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);
		}
	}

    按照Spring的Bean語義要求,對BeanDefinion進行解析並轉化為容器內部資料結構的,這個過程是在registerBeanDefinitions(doc, resource)中完成的。具體的過程是由BeanDefinitionDocumentReader來完成的, 這個registerBeanDefinition還對載人的Bean的數量進行了統計。具體過程如程式碼所示:

	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//這裡得到BeanDefinitionDocumentReader來對XML的BeanDefinition進行解析
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		int countBefore = getRegistry().getBeanDefinitionCount();
		//具體解析過程在這個registerBeanDefinitions中完成
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

    BeanDefinition的載入分成兩部分,首先通過呼叫XML的解析器得到document物件,但這些document物件並沒有按照Spring的Bean規則進行解析。在完成通用的XML解析以後,才是按照Spring的Bean規則進行解析的地方,這個按照Spring的Bean規則進行解析的過程是在documentReader中實現的。這裡使用的documentReader是預設設定好的  DefaultBeanDefinitionDocumentReader。這個DefaultBeanDefinitionDocumentReader的建立是在後面的方法中完成的,然後再完成BeanDefinition的處理,處理的結果由BeanDefinitionHolder物件來持有。這個BeanDefinitionHolder除了持有BeanDefinition物件外,還持有其他與BeanDefinition的使用相關的資訊,比如Bean 的名字、別名集合等。這個BeanDefinitionHolder的生成是通過對Document文件樹的內容進行解析來完成的,可以看到這個解析過程是由BeanDefinitionParserDelegate來實現(具體在processBeanDefinition方法中實現)的,同時這個解析是與Spring對BeanDefinition的配置規則緊密相關的。具體的實現原理如程式碼所示。

建立BeanDefinitionDocumentReader

	protected BeanDefinitionDocumentReader createBeanDefinitionDocumentReader() {
		return BeanDefinitionDocumentReader.class.cast(BeanUtils.instantiateClass(this.documentReaderClass));
	}


	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		//這裡得到BeanDefinitionDocumentReader來對XML的BeanDefinition進行解析
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		int countBefore = getRegistry().getBeanDefinitionCount();
		//具體解析過程在這個registerBeanDefinitions中完成
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

	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 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);
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isInfoEnabled()) {
						logger.info("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}

		preProcessXml(root);
		parseBeanDefinitions(root, this.delegate);//呼叫這個方法
		postProcessXml(root);

		this.delegate = parent;
	}




	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		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)) {
						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);
		}
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);//呼叫這個方法
		}
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}

	//這是處理BeanDefinition的地方,具體委託給BeanDefinitionParserDelegate來完成,ele對應Spring BeanDefinition中定義的XML元素
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		//BeanDefinitionHolder是BeanDefinition物件的封裝類,封裝了BeanDefinition的名字和別名。用它來完成向IoC容器的註冊。
		//得到這個BeanDefinitionHolder就意味著BeanDefinition是通過BeanDefinitionParserDelegate對XML元素的資訊按照Spring的Bean規則進行解析得到的
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				//這裡是向IoC容器註冊解析得到BeanDefinition的地方
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// Send registration event.
			//在BeanDefinition向IoC容器註冊完以後傳送訊息
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}

    具體的Spring BeanDefinition的解析是在BeanDefinitionParserDelegate中完成的。這個類裡包含了對各種Spring Bean定義規則的處理。在這裡會看到對那些熟悉的BeanDefinition定義的處理,比如id 、name 、aliase等屬性元素。把這些元素的值從XML檔案相應的元素的屬性中讀取出來以後,設定到生成的BeanDefinitionHolder中去。這些屬性的解析還是比較簡單的。對於其他元素配置的解析,比如各種Bean的屬性配置,通過一個較為複雜的解析過程,這個過程是由parseBeanDefinitionElement來完成的。解析完成以後,會把解析結果放到BeanDefinition物件中並設定到BeanDefinitionHolder中去,如程式碼所示:

	public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
		//這裡取得<bean>元素中定義的id、name和aliase屬性的值
		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, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
			aliases.addAll(Arrays.asList(nameArr));
		}

		String beanName = 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);
		}
		//這個方法會引發對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;
	}

    上面介紹了對Bean元素進行解析的過程,也就是BeanDefinition依據XML的 bean標籤定義被建立的過程。這個BeanDefinition可以看成是對 bean標籤定義的抽象,如圖所示。(Alt+7)

    這個資料物件中封裝的資料大多都是與 <bean>定義相關的,也有很多在定義Bean時看到的那些Spring標記,比如常見的init-method 、destroy-method 、factory-method , 等等,這個BeanDefinition資料型別是非常重要的,它封裝了很多基本資料,這些基本資料都是IoC容器需要的。有了這些基本資料, IoC容器才能對Bean配置進行處理, 才能實現相應的容器特性。

下面介紹下對BeanDefinition定義元素的處理:

	public AbstractBeanDefinition parseBeanDefinitionElement(
			Element ele, String beanName, BeanDefinition containingBean) {

		this.parseState.push(new BeanEntry(beanName));
		//這裡只讀取定義的<bean>中設定的class名字,然後載入到BeanDefinition中去,只是做個記錄,
		//並不涉及物件的例項化過程,物件的例項化實際上是在依賴注入時完成的
		String className = null;
		if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
			className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
		}

		try {
			String parent = null;
			if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
				parent = ele.getAttribute(PARENT_ATTRIBUTE);
			}
			//這裡生成需要的BeanDefinition物件,為Bean定義資訊的載入做準備
			AbstractBeanDefinition bd = createBeanDefinition(className, parent);
			//這裡對當前的Bean元素進行屬性解析,並設定description的資訊
			parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
			bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
			//從名字可以看到這是對各種<bean>元素的資訊進行解析的地方
			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;
		}
		//下面這些異常時配置Bean出現問題時經常看到的,這些檢查是在createBeanDefinition時進行的,
		// 會檢查Bean的class設計是否正確,比如這個類是否能找到
		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;
	}

    上面是具體生成BeanDefinition的地方。舉一個對property進行解析的例子來完成對整個BeanDefinition載入過程的分析,還是在類BeanDefinitionParserDelegate的程式碼中, 一層一層地對BeanDefinition中的定義進行解析,比如從屬性元素集合到具體的每一個屬性元素,然後才是對具體的屬性值的處理。根據解析結果,對這些屬性值的處理會被封裝成PropertyValue物件並設定到BeanDefinition物件中去,如程式碼所示。

	//便利所有Bean元素下定義的property元素
	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元素後對該property元素進行解析的過程
				parsePropertyElement((Element) node, bd);
			}
		}
	}



	public void parsePropertyElement(Element ele, BeanDefinition bd) {
		//獲取property的名字
		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 {
			//如果同一個Bean中已經有同名的property存在,則不進行解析,直接返回。
			//所以說如果同一個Bean中由同名的property設定,那麼起作用的只有第一個
			if (bd.getPropertyValues().contains(propertyName)) {
				error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
				return;
			}
			//這是解析property值的地方,返回的物件對應bean定義的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();
		}
	}



	//這裡取得property元素的值,也許是個list或其他
	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;
				}
			}
		}
		//這裡判斷property的屬性,是ref還是value,不允許同時是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,建立一個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,建立一個value的資料物件TypedStringValue,這個物件封裝了value的資訊
		else if (hasValueAttribute) {
			TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
			valueHolder.setSource(extractSource(ele));
			return valueHolder;
		}
		//如果還有子元素,觸發對子元素的解析
		else if (subElement != null) {
			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;
		}
	}

    這裡是對property子元素的解析過程, Array 、List 、Set 、Map 、Prop等各種元素都會在這裡進行解析,生成對應的資料物件,比如ManagedList 、ManagedArray 、ManagedSet等。這些Managed類是Spring對具體的BeanDefinition的資料封裝。

下面以對Property的元素進行解析的過程為例,通過它的實現來說明具體的解析過程是怎樣完成的,如程式碼所示:

對屬性元素進行解析:

	public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultValueType) {
		if (!isDefaultNamespace(ele)) {
			return parseNestedCustomElement(ele, bd);
		}
		else if (nodeNameEquals(ele, BEAN_ELEMENT)) {
			BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
			if (nestedBd != null) {
				nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
			}
			return nestedBd;
		}
		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 the same XML file.
				refName = ele.getAttribute(LOCAL_REF_ATTRIBUTE);
				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', 'local' 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;
		}
		else if (nodeNameEquals(ele, IDREF_ELEMENT)) {
			return parseIdRefElement(ele);
		}
		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;
		}
		else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {
			return parseArrayElement(ele, bd);
		}
		else if (nodeNameEquals(ele, LIST_ELEMENT)) {
			return parseListElement(ele, bd);
		}
		else if (nodeNameEquals(ele, SET_ELEMENT)) {
			return parseSetElement(ele, bd);
		}
		else if (nodeNameEquals(ele, MAP_ELEMENT)) {
			return parseMapElement(ele, bd);
		}
		else if (nodeNameEquals(ele, PROPS_ELEMENT)) {
			return parsePropsElement(ele);
		}
		else {
			error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
			return null;
		}
	}

    下面看看List這樣的屬性配置是怎樣被解析的,依然是在BeanDefinitionParscrDelegate中,返回的是一個List物件,這個List是Spring定義的ManagedList,作為封裝List這類配置定義的資料封裝,如程式碼所示:

	public List<Object> parseListElement(Element collectionEle, BeanDefinition bd) {
		String defaultElementType = collectionEle.getAttribute(VALUE_TYPE_ATTRIBUTE);
		NodeList nl = collectionEle.getChildNodes();
		ManagedList<Object> target = new ManagedList<Object>(nl.getLength());
		target.setSource(extractSource(collectionEle));
		target.setElementTypeName(defaultElementType);
		target.setMergeEnabled(parseMergeAttribute(collectionEle));
		//具體的List元素的解析過程
		parseCollectionElements(nl, target, bd, defaultElementType);
		return target;
	}



	protected void parseCollectionElements(
			NodeList elementNodes, Collection<Object> target, BeanDefinition bd, String defaultElementType) {
		//遍歷所有的元素節點,並判斷其型別是否為Element
		for (int i = 0; i < elementNodes.getLength(); i++) {
			Node node = elementNodes.item(i);
			if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
				//加入target中,target是一個ManagedList,同時觸發對下一層子元素的解析過程,這是一個遞迴的呼叫
				target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
			}
		}
	}

    經過這樣逐層地解析,我們在XML檔案中定義的BeanDefinition就被整個載入到了IoC容器中,並在容器中建立了資料對映。在IoC容器中建立了對應的資料結構,或者說可以看成是POJO物件在loC容器中的抽象,這些資料結構可以以AbstractBeanDefinition為入口,讓IoC容器執行索引、查詢和操作。簡單的POJO操作背後其實蘊含著一個複雜的抽過程,經過以上的載入過程, IoC容器大致完成了管理Bean物件的資料準備工作(或者說是初始化過程)。但是,重要的依賴注入實際上在這個時候還沒有發生,現在,在IoC 容器BeanDefinition 中存在的還只是一些靜態的配置資訊。嚴格地說,這時候的容器還沒有完全起作用,要完全發揮容器的作用,還需完成資料向容器的註冊。

BeanDefinition在IoC容器中的註冊

    前面已經分析過BeanDefinition在IoC容器中載入和解析的過程。在這些動作完成以後,使用者定義的BeanDefinition資訊已經在IoC容器內建立起了自己的資料結構以及相應的資料表示,但此時這些資料還不能供IoC容器直接使用,需要在IoC容器中對這些BeanDefinition資料進行註冊。這個註冊為IoC容器提供了更友好的使用方式,在DefaultListableBeanFactory中,是通過一個HashMap 來持有載入的BeanDefinition 的,這個HashMap 的定義在DefaultListableBeanFactory中可以看到,如下所示:

    將解析得到的BeanDefinition 向IoC容器中的beanDefinitionMap註冊的過程是在載入BeanDefinition完成後進行的,註冊的呼叫過程如圖所示。

    在DefaultListableBeanFactoryr和實現了BeanDefinitionRegistry的介面,這個介面的實現完成BeanDefinition向容器的註冊。這個註冊過程不復雜,就是把解析得到的BeanDefinition設定到JhashMap中去。需要注意的是,如果遇到同名的BeanDefinition , 進行處理的時候需要依據allowBeanDefin itionOverriding的配置來完成。具體的實現如程式碼所示。
 

    protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
        BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
        if (bdHolder != null) {
            bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);

            try {
                BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, this.getReaderContext().getRegistry());
            } catch (BeanDefinitionStoreException var5) {
                this.getReaderContext().error("Failed to register bean definition with name '" + bdHolder.getBeanName() + "'", ele, var5);
            }

            this.getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
        }

    }

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

		// Register bean definition under primary name.
		String beanName = definitionHolder.getBeanName();
		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);
			}
		}
	}


	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屬性中的methodOverrides進行校驗,
				// 校驗 methodOverrides是否與工廠方法並存或者methodOverrides對應的方法是否存在
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		// 處理註冊已經註冊的beanName情況
		if (existingDefinition != null) {
			// 如果對應的beanName已經註冊且在配置中配置了bean不允許被覆蓋,則丟擲異常。
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +
						"': There is already [" + existingDefinition + "] bound.");
			}
			else if (existingDefinition.getRole() < beanDefinition.getRole()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				if (logger.isWarnEnabled()) {
					logger.warn("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.isInfoEnabled()) {
					logger.info("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (logger.isDebugEnabled()) {
					logger.debug("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,保證資料的一致性
				synchronized (this.beanDefinitionMap) {
					//新增到beanDefinitionMap中
					this.beanDefinitionMap.put(beanName, beanDefinition);
					List<String> updatedDefinitions = new ArrayList<String>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					//按註冊順序列出bean定義名稱,進行覆蓋
					this.beanDefinitionNames = updatedDefinitions;
					//beanName名稱相同的情況
					if (this.manualSingletonNames.contains(beanName)) {
						Set<String> updatedSingletons = new LinkedHashSet<String>(this.manualSingletonNames);
						//刪除並新增,這也就是為什麼beanName相同情況下後者會把前者覆蓋
						updatedSingletons.remove(beanName);
						this.manualSingletonNames = updatedSingletons;
					}
				}
			}
			else {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				this.manualSingletonNames.remove(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

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

    完成了BeanDefinition的註冊,就完成了IoC容器的初始化過程。此時,在使用的IoC容器DefaultListableBeanFactory中已經建立了整個Bean的配置資訊,而且這些BeanDefinition 已經可以被容器檢索和使用了, 它們都在beanDefinitionMap裡被檢索和使用。 容器的作用就是對這些資訊進行處理和維護。這些資訊是容器建立依賴反轉的基礎,有了這些基礎資料, 下面我們看一下在IoC容器中,依賴注入是怎樣完成的。

參考《SPRING技術內幕》