深入浅出Mybatis系列(三)---配置详解之properties与environments(mybatis源码篇)

  上篇文章《深入浅出 Mybatis 系列(二)--- 配置简介(mybatis 源码篇)》我们通过对 mybatis 源码的简单分析,可看出,在 mybatis 配置文件中,在 configuration 根节点下面,可配置 properties、typeAliases、plugins、objectFactory、objectWrapperFactory、settings、environments、databaseIdProvider、typeHandlers、mappers 这些节点。那么本次,就会先介绍 properties 节点和 environments 节点。

  为了让大家能够更好地阅读 mybatis 源码,我先简单的给大家示例一下 properties 的使用方法。  

 1 <configuration>
 2 <!-- 方法一: 从外部指定 properties 配置文件, 除了使用 resource 属性指定外,还可通过 url 属性指定 url  
 3   <properties resource="dbConfig.properties"></properties> 
 4   -->
 5   <!-- 方法二: 直接配置为 xml -->
 6   <properties>
 7       <property name="driver" value="com.mysql.jdbc.Driver"/>
 8       <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
 9       <property name="username" value="root"/>
10       <property name="password" value="root"/>
11   </properties>

  那么,我要是 两种方法都同时用了,那么哪种方法优先?

  当以上两种方法都 xml 配置优先, 外部指定 properties 配置其次。至于为什么,接下来的源码分析会提到,请留意一下。

  再看一下 envirements 元素节点的使用方法吧:

<environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
          <!--
          如果上面没有指定数据库配置的 properties 文件,那么此处可以这样直接配置 
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/test1"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
         -->
     <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> 上面指定了数据库配置文件, 配置文件里面也是对应的这四个属性 </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
     <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="driver"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="${driver}"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
     <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="url"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="${url}"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
     <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="username"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="${username}"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
     <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="password"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="${password}"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
     
  <span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">dataSource</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">environment</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

<span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> 我再指定一个environment </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">environment </span><span style="color: rgba(255, 0, 0, 1)">id</span><span style="color: rgba(0, 0, 255, 1)">="test"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
  <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">transactionManager </span><span style="color: rgba(255, 0, 0, 1)">type</span><span style="color: rgba(0, 0, 255, 1)">="JDBC"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
  <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">dataSource </span><span style="color: rgba(255, 0, 0, 1)">type</span><span style="color: rgba(0, 0, 255, 1)">="POOLED"</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="driver"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="com.mysql.jdbc.Driver"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
    <span style="color: rgba(0, 128, 0, 1)">&lt;!--</span><span style="color: rgba(0, 128, 0, 1)"> 与上面的url不一样 </span><span style="color: rgba(0, 128, 0, 1)">--&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="url"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="jdbc:mysql://localhost:3306/demo"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="username"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="root"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
    <span style="color: rgba(0, 0, 255, 1)">&lt;</span><span style="color: rgba(128, 0, 0, 1)">property </span><span style="color: rgba(255, 0, 0, 1)">name</span><span style="color: rgba(0, 0, 255, 1)">="password"</span><span style="color: rgba(255, 0, 0, 1)"> value</span><span style="color: rgba(0, 0, 255, 1)">="root"</span><span style="color: rgba(0, 0, 255, 1)">/&gt;</span>
  <span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">dataSource</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>
<span style="color: rgba(0, 0, 255, 1)">&lt;/</span><span style="color: rgba(128, 0, 0, 1)">environment</span><span style="color: rgba(0, 0, 255, 1)">&gt;</span>

</environments>

  environments 元素节点可以配置多个 environment 子节点, 怎么理解呢? 

  假如我们系统的开发环境和正式环境所用的数据库不一样(这是肯定的), 那么可以设置两个 environment, 两个 id 分别对应开发环境(dev)和正式环境(final),那么通过配置 environments 的 default 属性就能选择对应的 environment 了, 例如,我将 environments 的 deault 属性的值配置为 dev, 那么就会选择 dev 的 environment。 至于这个是怎么实现的, 下面源码就会讲。

  好啦,上面简单给大家介绍了一下 properties 和 environments 的配置, 接下来就正式开始看源码了:

  上次我们说过 mybatis 是通过 XMLConfigBuilder 这个类在解析 mybatis 配置文件的,那么本次就接着看看 XMLConfigBuilder 对于 properties 和 environments 的解析:

XMLConfigBuilder:

  1 public class XMLConfigBuilder extends BaseBuilder {
  2 
  3     private boolean parsed;
  4     //xml 解析器
  5     private XPathParser parser;
  6     private String environment;
  7   
  8     //上次说到这个方法是在解析 mybatis 配置文件中能配置的元素节点
  9     //今天首先要看的就是 properties 节点和 environments 节点
 10     private void parseConfiguration(XNode root) {
 11         try {
 12           //解析 properties 元素
 13           propertiesElement(root.evalNode("properties")); //issue #117 read properties first
 14           typeAliasesElement(root.evalNode("typeAliases"));
 15           pluginElement(root.evalNode("plugins"));
 16           objectFactoryElement(root.evalNode("objectFactory"));
 17           objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
 18           settingsElement(root.evalNode("settings"));
 19           //解析 environments 元素
 20           environmentsElement(root.evalNode("environments")); // read it after objectFactory and objectWrapperFactory issue #631
 21           databaseIdProviderElement(root.evalNode("databaseIdProvider"));
 22           typeHandlerElement(root.evalNode("typeHandlers"));
 23           mapperElement(root.evalNode("mappers"));
 24         } catch (Exception e) {
 25           throw new BuilderException("Error parsing SQL Mapper Configuration. Cause:" + e, e);
 26         }
 27     }
 28   
 29     
 30     //下面就看看解析 properties 的具体方法
 31     private void propertiesElement(XNode context) throws Exception {
 32         if (context != null) {
 33           //将子节点的 name 以及 value 属性 set 进 properties 对象
 34           //这儿可以注意一下顺序,xml 配置优先, 外部指定 properties 配置其次
 35           Properties defaults = context.getChildrenAsProperties();
 36           //获取 properties 节点上 resource 属性的值
 37           String resource = context.getStringAttribute("resource");
 38           //获取 properties 节点上 url 属性的值, resource 和 url 不能同时配置
 39           String url = context.getStringAttribute("url");
 40           if (resource != null && url != null) {
 41             throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
 42           }
 43           //把解析出的 properties 文件 set 进 Properties 对象
 44           if (resource != null) {
 45             defaults.putAll(Resources.getResourceAsProperties(resource));
 46           } else if (url != null) {
 47             defaults.putAll(Resources.getUrlAsProperties(url));
 48           }
 49           //将 configuration 对象中已配置的 Properties 属性与刚刚解析的融合
 50           //configuration 这个对象会装载所解析 mybatis 配置文件的所有节点元素,以后也会频频提到这个对象
 51           //既然 configuration 对象用有一系列的 get/set 方法, 那是否就标志着我们可以使用 java 代码直接配置? 
 52           //答案是肯定的, 不过使用配置文件进行配置,优势不言而喻
 53           Properties vars = configuration.getVariables();
 54           if (vars != null) {
 55             defaults.putAll(vars);
 56           }
 57           //把装有解析配置 propertis 对象 set 进解析器, 因为后面可能会用到
 58           parser.setVariables(defaults);
 59           //set 进 configuration 对象
 60           configuration.setVariables(defaults);
 61         }
 62     }
 63     
 64     //下面再看看解析 enviroments 元素节点的方法
 65     private void environmentsElement(XNode context) throws Exception {
 66         if (context != null) {
 67             if (environment == null) {
 68                 //解析 environments 节点的 default 属性的值
 69                 //例如: <environments default="development">
 70                 environment = context.getStringAttribute("default");
 71             }
 72             //递归解析 environments 子节点
 73             for (XNode child : context.getChildren()) {
 74                 //<environment id="development">, 只有 enviroment 节点有 id 属性,那么这个属性有何作用?
 75                 //environments 节点下可以拥有多个 environment 子节点
 76                 //类似于这样: <environments default="development"><environment id="development">...</environment><environment id="test">...</environments>
 77                 //意思就是我们可以对应多个环境,比如开发环境,测试环境等, 由 environments 的 default 属性去选择对应的 enviroment
 78                 String id = child.getStringAttribute("id");
 79                 //isSpecial 就是根据由 environments 的 default 属性去选择对应的 enviroment
 80                 if (isSpecifiedEnvironment(id)) {
 81                     //事务, mybatis 有两种:JDBC 和 MANAGED, 配置为 JDBC 则直接使用 JDBC 的事务,配置为 MANAGED 则是将事务托管给容器, 
 82                     TransactionFactory txFactory = transactionManagerElement(child.evalNode("transactionManager"));
 83                     //enviroment 节点下面就是 dataSource 节点了,解析 dataSource 节点(下面会贴出解析 dataSource 的具体方法)
 84                     DataSourceFactory dsFactory = dataSourceElement(child.evalNode("dataSource"));
 85                     DataSource dataSource = dsFactory.getDataSource();
 86                     Environment.Builder environmentBuilder = new Environment.Builder(id)
 87                           .transactionFactory(txFactory)
 88                           .dataSource(dataSource);
 89                     //老规矩,会将 dataSource 设置进 configuration 对象
 90                     configuration.setEnvironment(environmentBuilder.build());
 91                 }
 92             }
 93         }
 94     }
 95     
 96     //下面看看 dataSource 的解析方法
 97     private DataSourceFactory dataSourceElement(XNode context) throws Exception {
 98         if (context != null) {
 99             //dataSource 的连接池
100             String type = context.getStringAttribute("type");
101             //子节点 name, value 属性 set 进一个 properties 对象
102             Properties props = context.getChildrenAsProperties();
103             //创建 dataSourceFactory
104             DataSourceFactory factory = (DataSourceFactory) resolveClass(type).newInstance();
105             factory.setProperties(props);
106             return factory;
107         }
108         throw new BuilderException("Environment declaration requires a DataSourceFactory.");
109     } 
110 }

  通过以上对 mybatis 源码的解读,相信大家对 mybatis 的配置又有了一个深入的认识。

  还有一个问题, 上面我们看到,在配置 dataSource 的时候使用了 ${driver} 这种表达式, 这种形式是怎么解析的?其实,是通过 PropertyParser 这个类解析:

PropertyParser:

/**
 * 这个类解析 ${} 这种形式的表达式
 */
public class PropertyParser {

public static String parse(String string, Properties variables) {
VariableTokenHandler handler
= new VariableTokenHandler(variables);
GenericTokenParser parser
= new GenericTokenParser("${", "}", handler);
return parser.parse(string);
}

private static class VariableTokenHandler implements TokenHandler {
private Properties variables;

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> VariableTokenHandler(Properties variables) {
  </span><span style="color: rgba(0, 0, 255, 1)">this</span>.variables =<span style="color: rgba(0, 0, 0, 1)"> variables;
}

</span><span style="color: rgba(0, 0, 255, 1)">public</span><span style="color: rgba(0, 0, 0, 1)"> String handleToken(String content) {
  </span><span style="color: rgba(0, 0, 255, 1)">if</span> (variables != <span style="color: rgba(0, 0, 255, 1)">null</span> &amp;&amp;<span style="color: rgba(0, 0, 0, 1)"> variables.containsKey(content)) {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> variables.getProperty(content);
  }
  </span><span style="color: rgba(0, 0, 255, 1)">return</span> "${" + content + "}"<span style="color: rgba(0, 0, 0, 1)">;
}

}
}

好啦,以上就是对于 properties 和 environments 元素节点的分析,比较重要的都在对于源码的注释中标出。本次文章到此结束,接下来的文章会继续分析其他节点的配置。