BeanDefinition的載入和解析


概念

第二個過程是BeanDefinition的載入。這個載入過程是把用戶定義好的Bean表示成IoC容器內部的數據結構,而這個容器內部的數據結構就是BeanDefinition。具體來說,這個BeanDefinition實際上就是POJO對象在IoC容器中的抽象,通過這個BeanDefinition定義的數據結構,使IoC容器能夠方便地對POJO對象也就是Bean進行管理。IoC容器對Bean的管理和依賴注入功能的實現,就是通過對持有的BeanDefinition進行各種相關操作完成的。


分析過程

  • 整個載入和解析過程也是從refresh()啟動的,該方法在FileSystemXmlApplicationContext的基類AbstractApplic-ationContext中實現,它詳細的描述了整個ApplicationContext的初始化過程,比如BeanFactory的更新,Mess-ageSource和PostProcessor的注冊,等等。這里看起來更像是對ApplicationContext進行初始化的模板或執行提綱,這個執行過程為Bean的生命周期管理提供了條件。

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()的地方,也就是創建實際BeanFactory的方法入口
		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) {
			// Destroy already created singletons to avoid dangling resources.
    //為防止Bean資源占用,在異常處理中,銷毀已經在前面過程中生成的單間Bean
			destroyBeans();

			// Reset 'active' flag.
			cancelRefresh(ex);

			// Propagate exception to caller.
			throw ex;
		}
	}
}</code></pre>


  • 之后就進行資源定位過程,定位完成后就開始載入過程(見圖一),因為之前創建好DefaultListBeanFactory后,將其“綁定”給XmlBeanDefinitionReader,由XmlBeanDefinitionReader繼續后續的定位和載入(圖二),所以這里的載入過程也由XmlBeanDefinitionReader來完成。需要注意的是,因為這里我們使用XML方式定義Bean,所以使用XmlBeanDefinitionReader來處理,如果使用了其他定義方式,就需要使用其他種類的BeanDefinitionReader來完成載入工作。

image.png


image.png


  • 這里調用的是loadBeanDefinitions(Resource res)方法,但這個方法在AbstractBeanDefinitionReader類里是沒有實現的,它是一個接口方法,具體的實現在XmlBeanDefinitionReader中。在讀取器中,需要得到代表XML文件的Resource,因為這個Resource對象封裝了對XML文件的I/O操作,所以讀取器可以在打開I/O流后得到 XML的文件對象。有了這個文件對象以后,就可以按照Spring的Bean定義規則來對這個XML的文檔樹進行解析。

//父類AbstractBeanDefinitionReader遍歷調用loadBeanDefinitions(resource) public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException { Assert.notNull(resources, "Resource array must not be null"); int counter = 0; for (Resource resource : resources) { counter += loadBeanDefinitions(resource); } return counter; } 

//子類XmlBeanDefinitionReader對loadBeanDefinitions(Resource resource)的具體實現
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
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&lt;EncodedResource&gt; currentResources = this.resourcesCurrentlyBeingLoaded.get();
	if (currentResources == null) {
		currentResources = new HashSet&lt;EncodedResource&gt;(4);
		this.resourcesCurrentlyBeingLoaded.set(currentResources);
	}
	if (!currentResources.add(encodedResource)) {
		throw new BeanDefinitionStoreException(
				&quot;Detected cyclic loading of &quot; + encodedResource + &quot; - check your import definitions!&quot;);
	}
//這里得到XML文件,並得到IO的InputSource准備進行讀取
	try {
		InputStream inputStream = encodedResource.getResource().getInputStream();
		try {
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
    //具體的讀取過程在doLoadBeanDefinitions中,是從特定的XML文件中實際載入的地方。
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		finally {
			inputStream.close();
		}
	}
	catch (IOException ex) {
		throw new BeanDefinitionStoreException(
				&quot;IOException parsing XML document from &quot; + encodedResource.getResource(), ex);
	}
	finally {
		currentResources.remove(encodedResource);
		if (currentResources.isEmpty()) {
			this.resourcesCurrentlyBeingLoaded.remove();
		}
	}

}

//子類XmlBeanDefinitionReader的doLoadBeanDefinitions方法
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
int validationMode = getValidationModeForResource(resource);
//這里取得XML的Document對象,如何獲得可詳細看源碼。
Document doc = this.documentLoader.loadDocument(
inputSource, getEntityResolver(), this.errorHandler, validationMode, isNamespaceAware());
//這里啟動對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);
}
}

//子類XmlBeanDefinitionReader的registerBeanDefinitions方法
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//得到BeanDefinitionDocumentReader來對XML進行解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
documentReader.setEnvironment(this.getEnvironment());
int countBefore = getRegistry().getBeanDefinitionCount();
//具體的解析過程在BeanDefinitionDocumentReader的registerBeanDefinitions中完成。
//createReaderContext(resource)返回一個ReaderContext對象,里面封裝了XmlBeanDefinitionReader等組件。
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}


  • BeanDefinition的載入分成兩部分,首先通過調用XML的解析器得到document對象,但這些document對象並沒有按照Spring的Bean規則進行解析。在完成通用的XML解析以后,才是按照Spring的Bean規則進行解析的地方,這個按照Spring的Bean規則進行解析的過程是在documentReader中實現的。這里使用的documentReader是默認設置好的DefaultBeanDefinitionDocumentReader。然后就完成BeanDefinition的處理,處理的結果由Bean-DefinitionHolder對象來持有。這個BeanDefinitionHolder除了持有BeanDefinition對象外,還持有其他與Bean-Definition的使用相關的信息,比如Bean的名字、別名集合等。這個BeanDefinitionHolder的生成是通過對Docu-ment文檔樹的內容進行解析來完成的,可以看到這個解析過程是由BeanDefinitionParserDelegate來實現(具體在processBeanDefinition方法中實現)的,同時這個解析是與Spring對BeanDefinition的配置規則緊密相關的。具體的實現原理如下代碼:

//DefaultBeanDefinitionDocumentReader中的registerBeanDefinitions方法
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
    //將封裝了XmlBeanDefinitionReader等組件的XmlReaderContext傳給DefaultBeanDefinitionDocumentReader,方便后續回調。
		this.readerContext = readerContext;
	logger.debug(&quot;Loading bean definitions&quot;);
	Element root = doc.getDocumentElement();

	doRegisterBeanDefinitions(root);

}

//DefaultBeanDefinitionDocumentReader中的doRegisterBeanDefinitions方法
protected void doRegisterBeanDefinitions(Element root) {
String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
if (StringUtils.hasText(profileSpec)) {
Assert.state(this.environment != null, "environment property must not be null");
String[] specifiedProfiles = StringUtils.tokenizeToStringArray(profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
if (!this.environment.acceptsProfiles(specifiedProfiles)) {
return;
}
}

	// any nested &lt;beans&gt; elements will cause recursion in this method. In
	// order to propagate and preserve &lt;beans&gt; 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 parent = this.delegate;
	this.delegate = createHelper(readerContext, root, parent);

	preProcessXml(root);
//利用BeanDefinitionParserDelegate進行解析的入口方法
	parseBeanDefinitions(root, this.delegate);
	postProcessXml(root);

	this.delegate = parent;

}

//DefaultBeanDefinitionDocumentReader中的parseBeanDefinitions方法
//遍歷子節點,也就是XML文件中的標簽,依次解析
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);
}
}

//DefaultBeanDefinitionDocumentReader中的parseDefaultElement方法
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);
}
//對"beans"標簽進行處理
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}

//DefaultBeanDefinitionDocumentReader中的processBeanDefinition方法
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//由BeanDefinitionParserDelegate負責解析,BeanDefinitionHolder是BeanDefinition的
//封裝類,用於完成向IoC容器的注冊
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
//載入解析完,注冊的入口函數
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}


  • 具體的Spring BeanDefinition的解析是在BeanDefinitionParserDelegate中完成的。這個類里包含了對各種Spri-ngBean定義規則的處理,感興趣可以仔細研究。比如我們最熟悉的對Bean元素的處理是怎樣完成的,也就是怎樣處理在XML定義文件中出現的<bean></bean>這個最常見的元素信息。在這里會看到對那些熟悉的Bean定義的處理,比如id, name, aliase等屬性元素。把這些元素的值從XML文件相應的元素的屬性中讀取出來以后,設置到生成的BeanDefinitionHolder中去。這些屬性的解析還是比較簡單的。對於其他元素配置的解析,比如各種Bean的屬性配置,通過一個較為復雜的解析過程,這個過程是由parseBeanDefinitionElement來完成的。解析完成以后。會把解析結果放到BeanDefinition對象中並設置到BeanDefinitionHolder中去。具體代碼如下:

//BeanDefinitionParserDelegate中的parseBeanDefinitionElement方法。
//這里ele是<bean>標簽,BeanDefinition可以看成是對<bean>定義的抽象,也就是存儲<bean>定義的數據結構,
//里面封裝的數據大多都是跟<bean>相關的,比如init-method,destroy-method等等,具體可以查看源碼,有了
//這些數據,IoC才能對Bean配置進行處理。
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, BeanDefinition containingBean) {
	  //這里取得在<bean>元素中定義的id,name和aliaes屬性的值	
    String id = ele.getAttribute(ID_ATTRIBUTE);
		String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
	List&lt;String&gt; aliases = new ArrayList&lt;String&gt;();
	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) &amp;&amp; !aliases.isEmpty()) {
		beanName = aliases.remove(0);
		if (logger.isDebugEnabled()) {
			logger.debug(&quot;No XML 'id' specified - using '&quot; + beanName +
					&quot;' as bean name and &quot; + aliases + &quot; as aliases&quot;);
		}
	}

	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 &amp;&amp;
							beanName.startsWith(beanClassName) &amp;&amp; beanName.length() &gt; beanClassName.length() &amp;&amp;
							!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
						aliases.add(beanClassName);
					}
				}
				if (logger.isDebugEnabled()) {
					logger.debug(&quot;Neither XML 'id' nor 'name' specified - &quot; +
							&quot;using generated bean name [&quot; + beanName + &quot;]&quot;);
				}
			}
			catch (Exception ex) {
				error(ex.getMessage(), ele);
				return null;
			}
		}
		String[] aliasesArray = StringUtils.toStringArray(aliases);
		return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
	}

	return null;

}

//BeanDefinitionParserDelegate中的parseBeanDefinitionElement方法
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, BeanDefinition containingBean) {

	this.parseState.push(new BeanEntry(beanName));
//這里只讀取定義的&lt;bean&gt;中設里的class名字.然后載入到BeanDefiniton中去,只是做個
//記錄.並不涉及對象的實例化過程,對象的實例化實際上是在依核注入時完成的
	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));
  
  //從名字可以清楚地看到.這里是對各種&lt;bean&gt;元素的信息進行解析的地方
		parseMetaElements(ele, bd);
		parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
		parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
  
  //解析&lt;bean&gt;的構造函數設置
		parseConstructorArgElements(ele, bd);
  //解析&lt;bean&gt;的property設置
		parsePropertyElements(ele, bd);
		parseQualifierElements(ele, bd);

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

		return bd;
	}
//下面這些異常是在配JBean出現問題時經常會看到的,這些檢查是在createBeanDefinition
//時進行的,會檢查Bean的class設置是否正確,比如這個類是否能找到。
	catch (ClassNotFoundException ex) {
		error(&quot;Bean class [&quot; + className + &quot;] not found&quot;, ele, ex);
	}
	catch (NoClassDefFoundError err) {
		error(&quot;Class that bean class [&quot; + className + &quot;] depends on not found&quot;, ele, err);
	}
	catch (Throwable ex) {
		error(&quot;Unexpected failure during bean definition parsing&quot;, ele, ex);
	}
	finally {
		this.parseState.pop();
	}

	return null;
}</code></pre>


  • 上面是具體生成BeanDefinition的地方。在這里,我們舉一個對property進行解析的例子來完成對整個BeanDefi-nition載入過程的分析,還是在類BeanDefinitionParserDelegate的代碼中,一層一層地對BeanDefinition中的定義進行解析,比如從屬性元素集合到具體的每一個屬性元素,然后才是對具體的屬性值的處理。根據解析結果,對這些屬性值的處理會被封裝成PropertyValue對象並設置到BeanDefinition對象中去,代碼如下:

//BeanDefinitionParserDelegate中的parsePropertyElements方法
public void parsePropertyElements(Element beanEle, BeanDefinition bd) {
    //遍歷所有Bean元素下定義得到property元素
		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);
			}
		}
	}

//BeanDefinitionParserDelegate中的parsePropertyElement方法
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中有同名的proper七y設里,那么起作用的只是第一個
if (bd.getPropertyValues().contains(propertyName)) {
error("Multiple 'property' definitions for property '" + propertyName + "'", ele);
return;
}
//這里是解析property值的地方,這個解析結果會在下面封裝到PropertyValue對象中。
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();
}
}

//BeanDefinitionParserDelegate中的parsePropertyValue方法
//這里獲取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 &lt; nl.getLength(); i++) {
		Node node = nl.item(i);
		if (node instanceof Element &amp;&amp; !nodeNameEquals(node, DESCRIPTION_ELEMENT) &amp;&amp;
				!nodeNameEquals(node, META_ELEMENT)) {
			// Child element is what we're looking for.
			if (subElement != null) {
				error(elementName + &quot; must not contain more than one sub-element&quot;, ele);
			}
			else {
				subElement = (Element) node;
			}
		}
	}

//這里判斷property的屬性是ref還是value,不允許同時是ref和value
	boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
	boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
	if ((hasRefAttribute &amp;&amp; hasValueAttribute) ||
			((hasRefAttribute || hasValueAttribute) &amp;&amp; subElement != null)) {
		error(elementName +
				&quot; is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element&quot;, ele);
	}

//如果是ref,創建一個ref的數據對象RuntimeBeanReference,這個對象封裝了ref的信息
	if (hasRefAttribute) {
		String refName = ele.getAttribute(REF_ATTRIBUTE);
		if (!StringUtils.hasText(refName)) {
			error(elementName + &quot; contains empty 'ref' attribute&quot;, 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;
	}
//如果是子元素,例如list,set等等,則對子元素進行解析
	else if (subElement != null) {
		return parsePropertySubElement(subElement, bd);
	}
	else {
		// Neither child element nor &quot;ref&quot; or &quot;value&quot; attribute found.
		error(elementName + &quot; must specify a ref or value&quot;, ele);
		return null;
	}
}</code></pre>


  • 這里我們看看對子元素的解析過程,具體是分析對list標簽的解析過程。其他標簽的解析可閱讀源碼。代碼如下:

//BeanDefinitionParserDelegate中的parsePropertySubElement方法,對property的子標簽進行解析 public Object parsePropertySubElement(Element ele, BeanDefinition bd, String defaultValueType) { if (!isDefaultNamespace(ele)) { return parseNestedCustomElement(ele, bd); } //子標簽為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 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; } //子標簽為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); } else if (nodeNameEquals(ele, PROPS_ELEMENT)) { return parsePropsElement(ele); } else { error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele); return null; } } 

//BeanDefinitionParserDelegate中的parseListElement方法,解析list標簽,將解析結果封裝在ManagedList中。
public List 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) {

	for (int i = 0; i &lt; elementNodes.getLength(); i++) {
		Node node = elementNodes.item(i);
		if (node instanceof Element &amp;&amp; !nodeNameEquals(node, DESCRIPTION_ELEMENT)) {
    //加入到target中,target是一個ManagedList,同時開始對下一層子元素的解析過程。是一個遞歸調用。
			target.add(parsePropertySubElement((Element) node, bd, defaultElementType));
		}
	}
}


  • 經過這樣逐層地解析,我們在XML文件中定義的Bean信息就被整個載入到了IoC容器中,並在容器中建立了數據映射。在IoC容器中建立了對應的數據結構,或者說可以看成是POJO對象在IoC容器中的抽象,這些數據結構可以以AbstractBeanDefinition為入口,讓IoC容器執行索引、查詢和操作。但是,重要的依賴注入實際上在這個時候還沒有發生,現在,在IoC容器BeanDefinition中存在的還只是一些靜態的配置信息。嚴格地說,這時候的容器還沒有完全起作用。要發揮容器的作用,還需要完成數據向容器的注冊。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM