原文出自:http://cmsblogs.comjava
在 XmlBeanDefinitionReader.doLoadDocument()
方法中作了兩件事情,一是調用 getValidationModeForResource()
獲取 XML 的驗證模式,二是調用 DocumentLoader.loadDocument()
獲取 Document 對象。上篇博客已經分析了獲取 XML 驗證模式(【死磕Spring】----- IOC 之 獲取驗證模型),這篇咱們分析獲取 Document 對象。spring
獲取 Document 的策略由接口 DocumentLoader 定義,以下:網絡
public interface DocumentLoader { Document loadDocument( InputSource inputSource, EntityResolver entityResolver, ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception; }
DocumentLoader 中只有一個方法 loadDocument()
,該方法接收五個參數:app
該方法由 DocumentLoader 的默認實現類 DefaultDocumentLoader 實現,以下:ide
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 對象。ui
經過 loadDocument()
獲取 Document 對象時,有一個參數 entityResolver ,該參數是經過 getEntityResolver()
獲取的。this
getEntityResolver()
返回指定的解析器,若是沒有指定,則構造一個未指定的默認解析器。url
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 。spa
getEntityResolver()
返回 EntityResolver ,那這個 EntityResolver 究竟是什麼呢?debug
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 聲明的地址改掉,以下:
若是咱們再次運行,則會報以下錯誤:
從上面的錯誤能夠看到,是在進行文檔驗證時,沒法根據聲明找到 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 對象。兩個參數聲明以下:
這兩個參數的實際內容和具體的驗證模式有關係。以下
以下:
咱們知道在 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 對象。
映射表以下(部分):