能夠這麼說,MyBatis初始化的過程,就是建立Configuration對象的過程。html
顧名思義,Configuration表示配置,該對象中維護了不少mybatis的配置參數。
大體可分爲四部分:mysql
經過查看org.apache.ibatis.mapping.Environment的源碼。
Environment僅維護了一個id,TransactionFactory以及DataSource。sql
Configuration提供了一些默認配置參數,並可經過get/set方法去修改參數值。
如mapUnderscoreToCamelCase,cacheEnabled等。apache
Configuration維護了不少緩存容器,如caches、resultMaps等,暫未深究設計模式
Configuration提供了InterceptorChain插件責任鏈,並對Mybatis的四大核心組件(Executor除外)進行攔截緩存
除了插件以外,其餘還有一些mapperRegistry用於註冊Mapper等,暫未深究網絡
Mybatis提供了兩種方式初始化Configurationmybatis
// 構建數據源,此處使用了Mybatis的PooledDataSource, 一般採用第三方數據源,如Druid PooledDataSource dataSource= new PooledDataSource(); dataSource.setDriver("com.mysql.jdbc.Driver"); dataSource.setUrl("jdbc:mysql://xxxx:3306/test"); dataSource.setUsername("username"); dataSource.setPassword("password"); // 構建環境 並將其標識爲dev Environment dev = new Environment("dev", new JdbcTransactionFactory(), dataSource); // 構建Configuration Configuration config= new Configuration(dev);
MyBatis提供XMLConfigBuilder經過XML構建Configuration。app
而MyBatis解析XML主要經過如下三個類: 2.1 XMLMapperEntityResolver 獲取XML本地dtd,避免從網絡獲取 2.2 XPathParser 解析XML爲Document對象,可獲取子節點 封裝細節: 2.2.1 獲取Document -> createDocument() DocumentBuilderFactory.newInstance().newDocumentBuilder().parse() 2.2.2 獲取子節點XNode及其餘類型子節點 -> evalXX().. xpath.evaluate() //xpath由XPathParser初始化時建立 -> XPathFactory.newInstance().newXPath() 2.3 XNode XNode 對Node以及XPathParser進行了封裝,可獲取子節點及節點屬性 2.3.1 獲取子節點 -> evalXX() 在2.2.2中說明了XPathParser經過xpath.evaluate 獲取Node節點,並返回XNode(實際是對Node以及XPathParser進行了封裝) 而XNode獲取子節點實際仍是經過XPathParser獲取。 2.3.2 獲取節點屬性 -> getXXAttribute() XNode初始化時,經過Node獲取節點屬性,並解析爲Properties類型,提供屬性獲取。 MyBatis實際上經過XPathParser和XNode封裝了經過DocumentBuilder解析XML爲Document,以及經過XPath解析節點屬性的過程。
XMLConfigbuilder則經過XPathParser和XNode獲取XML的配置屬性,
實現了Configuration的初始化(實現方法:XMlConfigBuilder.parseConfiguration)ui
貼一張 MyBatis3 的XML配置結構圖
資料來源:MyBatis3 XML配置
最後,在結尾總結一下Configuration初始化時涉及的設計模式工廠模式:TransactionFactory動態代理模式:InterceptorChain 此處名稱採用了責任鏈,其實是經過Plugin動態代理嵌套實現。