【死磕 Spring】----- IOC 之 獲取 Document 對象


原文出自:http://cmsblogs.com

XmlBeanDefinitionReader.doLoadDocument() 方法中做了兩件事情,一是調用 getValidationModeForResource() 獲取 XML 的驗證模式,二是調用 DocumentLoader.loadDocument() 獲取 Document 對象。上篇博客已經分析了獲取 XML 驗證模式(【死磕Spring】----- IOC 之 獲取驗證模型),這篇我們分析獲取 Document 對象。

獲取 Document 的策略由接口 DocumentLoader 定義,如下:

public interface DocumentLoader {
	Document loadDocument(
			InputSource inputSource, EntityResolver entityResolver,
			ErrorHandler errorHandler, int validationMode, boolean namespaceAware)
			throws Exception;

}

DocumentLoader 中只有一個方法 loadDocument() ,該方法接收五個參數:

  • inputSource:加載 Document 的 Resource 源
  • entityResolver:解析文件的解析器
  • errorHandler:處理加載 Document 對象的過程的錯誤
  • validationMode:驗證模式
  • namespaceAware:命名空間支持。如果要提供對 XML 名稱空間的支持,則為true

該方法由 DocumentLoader 的默認實現類 DefaultDocumentLoader 實現,如下:

	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);
		return builder.parse(inputSource);
	}

首先調用 createDocumentBuilderFactory() 創建 DocumentBuilderFactory ,再通過該 factory 創建 DocumentBuilder,最后解析 InputSource 返回 Document 對象。

EntityResolver

通過 loadDocument() 獲取 Document 對象時,有一個參數 entityResolver ,該參數是通過 getEntityResolver() 獲取的。

getEntityResolver() 返回指定的解析器,如果沒有指定,則構造一個未指定的默認解析器。

	protected EntityResolver getEntityResolver() {
		if (this.entityResolver == null) {
			ResourceLoader resourceLoader = getResourceLoader();
			if (resourceLoader != null) {
				this.entityResolver = new ResourceEntityResolver(resourceLoader);
			}
			else {
				this.entityResolver = new DelegatingEntityResolver(getBeanClassLoader());
			}
		}
		return this.entityResolver;
	}

如果 ResourceLoader 不為 null,則根據指定的 ResourceLoader 創建一個 ResourceEntityResolver。如果 ResourceLoader 為null,則創建 一個 DelegatingEntityResolver,該 Resolver 委托給默認的 BeansDtdResolver 和 PluggableSchemaResolver 。

  • ResourceEntityResolver:繼承自 EntityResolver ,通過 ResourceLoader 來解析實體的引用。
  • DelegatingEntityResolver:EntityResolver 的實現,分別代理了 dtd 的 BeansDtdResolver 和 xml schemas 的 PluggableSchemaResolver。
  • BeansDtdResolver : spring bean dtd 解析器。EntityResolver 的實現,用來從 classpath 或者 jar 文件加載 dtd。
  • PluggableSchemaResolver:使用一系列 Map 文件將 schema url 解析到本地 classpath 資源

getEntityResolver() 返回 EntityResolver ,那這個 EntityResolver 到底是什么呢?

If a SAX application needs to implement customized handling for external entities, it must implement this interface and register an instance with the SAX driver using the setEntityResolver method.

就是說:如果 SAX 應用程序需要實現自定義處理外部實體,則必須實現此接口並使用 setEntityResolver() 向 SAX 驅動器注冊一個實例。

如下:

   public class MyResolver implements EntityResolver {
     public InputSource resolveEntity (String publicId, String systemId){
       if (systemId.equals("http://www.myhost.com/today")){
         MyReader reader = new MyReader();
         return new InputSource(reader);
       } else {
            // use the default behaviour
            return null;
       }
     }
   }

我們首先將 spring-student.xml 文件中的 XSD 聲明的地址改掉,如下:

spring-201806061001

如果我們再次運行,則會報如下錯誤:

spring-201806071001

從上面的錯誤可以看到,是在進行文檔驗證時,無法根據聲明找到 XSD 驗證文件而導致無法進行 XML 文件驗證。在(【死磕Spring】----- IOC 之 獲取驗證模型)中講到,如果要解析一個 XML 文件,SAX 首先會讀取該 XML 文檔上的聲明,然后根據聲明去尋找相應的 DTD 定義,以便對文檔進行驗證。默認的加載規則是通過網絡方式下載驗證文件,而在實際生產環境中我們會遇到網絡中斷或者不可用狀態,那么就應用就會因為無法下載驗證文件而報錯。

EntityResolver 的作用就是應用本身可以提供一個如何尋找驗證文件的方法,即自定義實現。

接口聲明如下:

public interface EntityResolver {
    public abstract InputSource resolveEntity (String publicId,String systemId) 
        throws SAXException, IOException;
}

接口方法接收兩個參數 publicId 和 systemId,並返回 InputSource 對象。兩個參數聲明如下:

  • publicId:被引用的外部實體的公共標識符,如果沒有提供,則返回null
  • systemId:被引用的外部實體的系統標識符

這兩個參數的實際內容和具體的驗證模式有關系。如下

如下:

spring-201806071002

spring-201806071003

我們知道在 Spring 中使用 DelegatingEntityResolver 為 EntityResolver 的實現類,resolveEntity() 實現如下:

	public InputSource resolveEntity(String publicId, @Nullable String systemId) throws SAXException, IOException {
		if (systemId != null) {
			if (systemId.endsWith(DTD_SUFFIX)) {
				return this.dtdResolver.resolveEntity(publicId, systemId);
			}
			else if (systemId.endsWith(XSD_SUFFIX)) {
				return this.schemaResolver.resolveEntity(publicId, systemId);
			}
		}
		return null;
	}

不同的驗證模式使用不同的解析器解析,如果是 DTD 驗證模式則使用 BeansDtdResolver 來進行解析,如果是 XSD 則使用 PluggableSchemaResolver 來進行解析。

BeansDtdResolver 的解析過程如下:

	public InputSource resolveEntity(String publicId, @Nullable String systemId) throws IOException {
		if (logger.isTraceEnabled()) {
			logger.trace("Trying to resolve XML entity with public ID [" + publicId +
					"] and system ID [" + systemId + "]");
		}
		if (systemId != null && systemId.endsWith(DTD_EXTENSION)) {
			int lastPathSeparator = systemId.lastIndexOf('/');
			int dtdNameStart = systemId.indexOf(DTD_NAME, lastPathSeparator);
			if (dtdNameStart != -1) {
				String dtdFile = DTD_NAME + DTD_EXTENSION;
				if (logger.isTraceEnabled()) {
					logger.trace("Trying to locate [" + dtdFile + "] in Spring jar on classpath");
				}
				try {
					Resource resource = new ClassPathResource(dtdFile, getClass());
					InputSource source = new InputSource(resource.getInputStream());
					source.setPublicId(publicId);
					source.setSystemId(systemId);
					if (logger.isDebugEnabled()) {
						logger.debug("Found beans DTD [" + systemId + "] in classpath: " + dtdFile);
					}
					return source;
				}
				catch (IOException ex) {
					if (logger.isDebugEnabled()) {
						logger.debug("Could not resolve beans DTD [" + systemId + "]: not found in classpath", ex);
					}
				}
			}
		}
or wherever.
		return null;
	}

從上面的代碼中我們可以看到加載 DTD 類型的 BeansDtdResolver.resolveEntity() 只是對 systemId 進行了簡單的校驗(從最后一個 / 開始,內容中是否包含 spring-beans),然后構造一個 InputSource 並設置 publicId、systemId,然后返回。

PluggableSchemaResolver 的解析過程如下:

	public InputSource resolveEntity(String publicId, @Nullable String systemId) throws IOException {
		if (logger.isTraceEnabled()) {
			logger.trace("Trying to resolve XML entity with public id [" + publicId +
					"] and system id [" + systemId + "]");
		}

		if (systemId != null) {
			String resourceLocation = getSchemaMappings().get(systemId);
			if (resourceLocation != null) {
				Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
				try {
					InputSource source = new InputSource(resource.getInputStream());
					source.setPublicId(publicId);
					source.setSystemId(systemId);
					if (logger.isDebugEnabled()) {
						logger.debug("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
					}
					return source;
				}
				catch (FileNotFoundException ex) {
					if (logger.isDebugEnabled()) {
						logger.debug("Couldn't find XML schema [" + systemId + "]: " + resource, ex);
					}
				}
			}
		}
		return null;
	}

首先調用 getSchemaMappings() 獲取一個映射表(systemId 與其在本地的對照關系),然后根據傳入的 systemId 獲取該 systemId 在本地的路徑 resourceLocation,最后根據 resourceLocation 構造 InputSource 對象。

映射表如下(部分):

spring-201806071004


免責聲明!

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



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