基於Xml 的IOC 容器-準備文件物件

Leon_Jinhai_Sun發表於2020-11-14

DocumentLoader 將Bean 配置資源轉換成Document 物件的原始碼如下:

//使用標準的JAXP將載入的Bean定義資源轉換成document物件
@Override
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);
	//解析Spring的Bean定義資源
	return builder.parse(inputSource);
}

protected DocumentBuilderFactory createDocumentBuilderFactory(int validationMode, boolean namespaceAware)
		throws ParserConfigurationException {

	//建立文件解析工廠
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	factory.setNamespaceAware(namespaceAware);

	//設定解析XML的校驗
	if (validationMode != XmlValidationModeDetector.VALIDATION_NONE) {
		factory.setValidating(true);
		if (validationMode == XmlValidationModeDetector.VALIDATION_XSD) {
			// Enforce namespace aware for XSD...
			factory.setNamespaceAware(true);
			try {
				factory.setAttribute(SCHEMA_LANGUAGE_ATTRIBUTE, XSD_SCHEMA_LANGUAGE);
			}
			catch (IllegalArgumentException ex) {
				ParserConfigurationException pcex = new ParserConfigurationException(
						"Unable to validate using XSD: Your JAXP provider [" + factory +
						"] does not support XML Schema. Are you running on Java 1.4 with Apache Crimson? " +
						"Upgrade to Apache Xerces (or Java 1.5) for full XSD support.");
				pcex.initCause(ex);
				throw pcex;
			}
		}
	}

	return factory;
}

上面的解析過程是呼叫JavaEE 標準的JAXP 標準進行處理。至此Spring IOC 容器根據定位的Bean 配置資訊,將其載入讀入並轉換成為Document 物件過程完成。接下來我們要繼續分析Spring IOC 容器將載入的Bean 配置資訊轉換為Document 物件之後,是如何將其解析為Spring IOC 管理的Bean 物件並將其註冊到容器中的。

 

 

 

相關文章