1. 程式人生 > >Mybatis 原始碼解析(三)

Mybatis 原始碼解析(三)

文章個人學習原始碼所得,若存在不足或者錯誤之處,請大家指出。

Properties配置格式如下:
Configuration.xml中:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <properties>
        <property name="username"
value="cig-root"/>
<property name="password" value="cig-root"/> </properties> ... </configuration>

當然properties的資訊也可以配置到.properties檔案中:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=UTF-8
username=root
password=root

對於properties節點的解析沒有什麼好說的,主要是properties可以在不同的位置進行設定,例如可以在:
SqlSessionFactoryBuilder的SqlSessionFactory buid(Reader reader, Properties properties)傳入,那麼這幾種properties的載入順序是什麼呢。
按照優先順序由低到高來說明:
1) SqlSessionFactoryBuilder例項build時傳入,這種properties的設定方式優先順序是最低的,當後續配置檔案中讀取到相應的值時,會將SqlSessionFactory buid(Reader reader, Properties properties)時傳入的properties全部沖掉,所以在使用時要注意。
2) Configuration.xml中properties標籤下內容,當解析到properties標籤時,會先將properties標籤下子標籤的值解析出來,例如上面的username=cig-root和password=cig-root。
3) .properties檔案是優先順序最高的,當之前所有的properties資訊解析完畢後,會對.properties檔案進行解析,解析時,會覆蓋Configuration.xml中同名的資訊,例如上面.properties檔案中的username=root和password=root會覆蓋掉username=cig-root和password=cig-root,所以在配置時要注意儘量不要在多個地方對其進行配置。