通俗理解spring源碼(三)—— 獲取xml的驗證模式

来源:https://www.cnblogs.com/xiaohang123/archive/2020/04/15/12709192.html
-Advertisement-
Play Games

通俗理解spring源碼(三)—— 獲取xml的驗證模式 上一篇講到了xmlBeanDefinitionReader.doLoadBeanDefinitions(inputSource, encodedResource.getResource())方法。 protected int doLoadBe ...


通俗理解spring源碼(三)—— 獲取xml的驗證模式

上一篇講到了xmlBeanDefinitionReader.doLoadBeanDefinitions(inputSource, encodedResource.getResource())方法。

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
            throws BeanDefinitionStoreException {

        try {
            //從資源文件轉換為document對象
            Document doc = doLoadDocument(inputSource, resource);
            //解析document,並註冊beanDefiniton到工廠中
            int count = registerBeanDefinitions(doc, resource);
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded " + count + " bean definitions from " + resource);
            }
            return count;
        }
        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);
        }
    }

 在該方法中,首先就是將資源文件裝換為document對象

    protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
        return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
                getValidationModeForResource(resource), isNamespaceAware());
    }

   通過getValidationModeForResource(resource)獲取xml文件的驗證模式。

xml文件有兩種校驗模式,DTD和XSD,這裡簡單介紹一下:

1、DTD校驗模式

DTD(Document Type Definition)即文檔類型定義,是一種xml約束模式語言,是xml文件的驗證機制,屬於xml文件的一部分。DTD是一種保證xml文檔格式正確的有效方法,可以通過比較xml文檔和DTD文件來看文檔是否符合規範,元素和標簽使用是或否正確。一個DTD文檔包含:元素的定義規則,元素間關係的定義規則,元素可使用的屬性,可使用的實體或符號規則。

這個DTD文件,可以直接寫在xml內部,如:

<?xml version="1.0"?>
<!DOCTYPE note [
  <!ELEMENT note (to,from,heading,body)>
  <!ELEMENT to      (#PCDATA)>
  <!ELEMENT from    (#PCDATA)>
  <!ELEMENT heading (#PCDATA)>
  <!ELEMENT body    (#PCDATA)>
]>
<note>
  <to>George</to>
  <from>John</from>
  <heading>Reminder</heading>
  <body>Don't forget the meeting!</body>
</note>

也可以外部引用,比如將DTD內容寫在與xml文件同目錄的note.dtd中,如:

<?xml version="1.0"?>
<!DOCTYPE note SYSTEM "note.dtd">
<note>
<to>George</to>
<from>John</from>
<heading>Reminder</heading>
<body>Don't forget the meeting!</body>
</note> 

   還可以引用網路上的DTD文件,如在我們最熟悉的mybatis配置文件中:

<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

  引用外部DTD文件,一定會有<!DOCTYPE >聲明!

  關於DTD文檔的詳細語法,可以參考https://www.w3school.com.cn/dtd/index.asp

2、XSD驗證模式

  XML Schema語言就是XSD(XML Schemas Definition)。XML Schema描述了xml文檔的結構,可以用一個指定的XML Schema來驗證某個XML文檔,以檢查該xml文檔是否符合要求。文檔設計者可以通過XML Schema指定xml文檔所允許的結構和內容,並可據此檢查xml文檔是否是有效的。XML Schema本身是xml文檔,它符合xml語法結構。可以用通用的xml‘解析器解析它。

  XSD比DTD更加強大,可針對未來的需求進行擴展,基於 XML 編寫,支持數據類型,支持命名空間等。

  一個xml文件中可以引入多個命名空間,每個命名空間都要與一個首碼綁定,或者沒有首碼,作為預設命名空間,並且每個命名空間都要指定其對應的xml Schema文件位置或URL位置,如在spring配置文件中:

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">

</beans>

  其中,

xmlns="http://www.springframework.org/schema/beans
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd

  表示引入beans作為預設命名空間,相對應的xsd文件在http://www.springframework.org/schema/beans/spring-beans-4.3.xsd中,要使用該命名空間的標簽,不用加首碼。

xmlns:context="http://www.springframework.org/schema/context"
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd

   表示引入context命名空間,並與context首碼相綁定,相對應的xsd文件在http://www.springframework.org/schema/context/spring-context-4.3.xsd中,即要使用該命名空間的標簽,需要加context首碼,比如說我們最熟悉的  <context:component-scan base-package=""></context:component-scan>。

  關於XSD文檔的詳細語法,可以參考https://www.w3school.com.cn/schema/index.asp

 3、驗證模式的讀取

  瞭解了DTD和XSD的區別後再去分析spring中對於驗證模式的獲取就容易多了。

  接著來看getValidationModeForResource(resource)。

    protected int getValidationModeForResource(Resource resource) {
        int validationModeToUse = getValidationMode();
        if (validationModeToUse != VALIDATION_AUTO) {
            return validationModeToUse;
        }
        int detectedMode = detectValidationMode(resource);
        if (detectedMode != VALIDATION_AUTO) {
            return detectedMode;
        }
        // Hmm, we didn't get a clear indication... Let's assume XSD,
        // since apparently no DTD declaration has been found up until
        // detection stopped (before finding the document's root tag).
        return VALIDATION_XSD;
    }

   這裡邏輯很簡單,作者的註釋也很有意思,就是說我們無法清楚的知道準確的驗證模式,如果在找到文檔的根標簽之前還沒有找到明顯的DTD聲明,則推測為XSD驗證模式。

  繼續看一下detectValidationMode(resource)方法:

    protected int detectValidationMode(Resource resource) {
        if (resource.isOpen()) {
            throw new BeanDefinitionStoreException(
                    "Passed-in Resource [" + resource + "] contains an open stream: " +
                    "cannot determine validation mode automatically. Either pass in a Resource " +
                    "that is able to create fresh streams, or explicitly specify the validationMode " +
                    "on your XmlBeanDefinitionReader instance.");
        }

        InputStream inputStream;
        try {
            inputStream = resource.getInputStream();
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(
                    "Unable to determine validation mode for [" + resource + "]: cannot open InputStream. " +
                    "Did you attempt to load directly from a SAX InputSource without specifying the " +
                    "validationMode on your XmlBeanDefinitionReader instance?", ex);
        }

        try {
            return this.validationModeDetector.detectValidationMode(inputStream);
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException("Unable to determine validation mode for [" +
                    resource + "]: an error occurred whilst reading from the InputStream.", ex);
        }
    }

   又是委派模式,由validationModeDetector進行處理,進入validationModeDetector.detectValidationMode(inputStream)中:

    public int detectValidationMode(InputStream inputStream) throws IOException {
        // Peek into the file to look for DOCTYPE.
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            boolean isDtdValidated = false;
            String content;
            //一行行讀取文件內容
            while ((content = reader.readLine()) != null) {
                //去掉文件的註釋內容
                content = consumeCommentTokens(content);
                if (this.inComment || !StringUtils.hasText(content)) {
                    continue;
                }
                //判斷該行是否包含DOCTYPE這個字元串
                if (hasDoctype(content)) {
                    isDtdValidated = true;
                    break;
                }
                //判斷該行是否包含開始標簽符號,即"<"
                if (hasOpeningTag(content)) {
                    // End of meaningful data...
                    break;
                }
            }
            return (isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD);
        }
        catch (CharConversionException ex) {
            // Choked on some character encoding...
            // Leave the decision up to the caller.
            return VALIDATION_AUTO;
        }
        finally {
            reader.close();
        }
    }

    private boolean hasDoctype(String content) {
        return content.contains(DOCTYPE);
    }
    private boolean hasOpeningTag(String content) {
        if (this.inComment) {
            return false;
        }
        int openTagIndex = content.indexOf('<');
        return (openTagIndex > -1 && (content.length() > openTagIndex + 1) &&
                Character.isLetter(content.charAt(openTagIndex + 1)));
    }

  一行行讀取文件內容,去掉文件的註釋內容,首先判斷該行是否包含DOCTYPE這個字元串,如果有則判定為VALIDATION_DTD,如果沒有,再判斷該行是否包含開始標簽符號,如果有,則判定VALIDATION_XSD,如果沒有,則讀取下一行。

 

  獲取xml驗證模式的邏輯並不複雜,主要是要知道DTD和XSD的區別。

  走的太遠,不要忘記為什麼出發!獲取校驗模式的目的是要對xml文件進行校驗,然後解析成document。

    protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
        return this.documentLoader.loadDocument(inputSource, getEntityResolver(), this.errorHandler,
                getValidationModeForResource(resource), isNamespaceAware());
    }

   下一章將講解documentLoader.loadDocument,獲取Document。

 

參考:https://www.w3school.com.cn/

   https://www.cnblogs.com/osttwz/p/6892999.html

   spring源碼深度解析


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 北航OO(2020)第二單元博客作業 [TOC] 設計策略分析(多線程視角) 本單元的三次作業中,我採用了相似的策略:採用輸入線程與電梯線程通過線程安全的調度器進行交互的方式。這種方式基本屬於生產者 消費者模式。在調度器的設計方面,我主要採用synchronized關鍵字結合wait和notify方 ...
  • 前言 這是一個基於中小型企業或團隊的架構設計。 不考慮大廠。有充分的理由相信,大廠有絕對的實力來搭建一個相當複雜的環境。 中小型企業或團隊是個什麼樣子? 開發團隊人員配置不全,部分人員身兼開發過程上下游的數個職責; 沒有專職的維護人員,或者維護人員實力不足以完全掌控生產和開發環境。 這種情況下,過於 ...
  • 無處不在的線程,多線程,阻塞隊列,併發 編程世界無新鮮事,看你翻牆翻得厲不厲害 場景:現在的軟體開發迭代速度(一周一更新,甚至一天一發佈)真是太快了,今天進行軟體更新的時候,看到了有趣的現象,這不就是線程池,ThreadPoolExecutor,阻塞隊列,任務(下載和安裝)最好的案例嘛!經常看到很多 ...
  • redis為什麼那麼快?結論有三點,大家都知道,這裡主要是分析。 首先第一點 redis是記憶體訪問的,所以快 當然這個大家都知道,所以不是重點 io密集型和cpu密集型 一般我們把任務分為io密集型和cpu密集型 io密集型 IO密集型指的是系統的CPU性能相對硬碟、記憶體要好很多,此時,系統運作,大 ...
  • 一、製作Nine-Patch圖片 1.含義:一種被特殊處理的png圖片,能夠指定哪些區域可以被拉伸,哪些區域不可以被拉伸。 2.首先先製作一個佈局 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xml ...
  • 實例級別的鎖 實例代碼 @Slf4j public class AddCompareDemo { private int a, b; public void add() { for (int i = 0; i < 10000; i++) { a++; b++; } } public void com ...
  • ThreadLocal ThreadLocal 適用於變數線上程間隔離,而在方法或類間共用的場景。 代碼 1 @RestController 2 public class ThreadLocalController { 3 private static final ThreadLocal<Strin ...
  • 指針是一個代表著某個記憶體地址的值, 這個記憶體地址往往是在記憶體中存儲的另一個變數的值的起始位置. Go語言對指針的支持介於Java語言和 C/C++ 語言之間, 它既沒有像Java那樣取消了代碼對指針的直接操作的能力, 也避免了 C/C++ 中由於對指針的濫用而造成的安全和可靠性問題. 指針地址和變數 ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...