分析java
MyBatis整合Spring的實現(2)中屬性能夠知道,XPathParser類在XMLConfigBuilder中充當了很是重要的角色,下面就來分析XPathParser的做用。app
1 屬性ui
1.1 XPathParser屬性:this
/** 整個XML文檔 */ private Document document; /** 是否已驗證,true:是,false:否 */ private boolean validation; /** 用於解析實體的基本接口 */ private EntityResolver entityResolver; /** 屬性 */ private Properties variables; /** XPath提供了對XPath計算環境和表達式的訪問 */ private XPath xpath;
2 構造器spa
XPathParser實例化的構造器爲:.net
3 方法code
根據構造器能夠看出,通過2個方法,最後生成了Document。orm
3.1 commonConstructorblog
方法中只是把屬性放入相應的值。接口
3.2 createDocument方法
private Document createDocument(InputSource inputSource) { // important: this must only be called AFTER common constructor try { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); factory.setValidating(validation); factory.setNamespaceAware(false); factory.setIgnoringComments(true); factory.setIgnoringElementContentWhitespace(false); factory.setCoalescing(false); factory.setExpandEntityReferences(true); DocumentBuilder builder = factory.newDocumentBuilder(); builder.setEntityResolver(entityResolver); builder.setErrorHandler(new ErrorHandler() { public void error(SAXParseException exception) throws SAXException { throw exception; } public void fatalError(SAXParseException exception) throws SAXException { throw exception; } public void warning(SAXParseException exception) throws SAXException { } }); return builder.parse(inputSource); } catch (Exception e) { throw new BuilderException("Error creating document instance. Cause: " + e, e); } }
這裏就是JDK底層提供的建立一個Document,這裏須要本身去查看JDK API,不在過多的分析。
4 MyBatis配置解析(XMLMapperEntityResolver)
上面只是看到代碼解析成Document文檔,可是MyBatis是如何找到本身的文檔的呢?下面就來分析。
MyBatis整合Spring的實現(2)中2.1已經提到「默認DTD文件解析類(XMLMapperEntityResolver)「。那麼就看這裏代碼如何。
圖中紅框中發現了,MyBatis配置的全局配置文件定義。
4.1 XMLMapperEntityResolver的接口EntityResolver
EntityResolver用於解析實體的基本接口。只提供了一個方法resolveEntity,且子類必須實現。
4.2 resolveEntity方法
代碼先根據publicId獲取InputSource,若是沒有,在根據systemId獲取InputSource。
總結:
通過3章的分析,瞭解Mybatis若是對全局配置文件進行讀取並生成Document。以上的類中已經不少能夠公用的,好比XPathParser類,沒有具體的邏輯代碼,只是一個XML到Document的轉換,因此後面分析的Mybatis對SQL配置的解析也使用了此類。本文4中XMLMapperEntityResolver類也已經把SQL的Mapper文件考慮進去。