Mybaits源码分析三之XMLConfigBuilder类properties 标签解析

在解析mybatis配置文件中,各个类型的配置顺序依次为

 1 private void parseConfiguration(XNode root) {
 2     try {
 3       //issue #117 read properties first
 4       propertiesElement(root.evalNode("properties"));
 5       Properties settings = settingsAsProperties(root.evalNode("settings"));
 6       loadCustomVfs(settings);
 7       typeAliasesElement(root.evalNode("typeAliases"));
 8       pluginElement(root.evalNode("plugins"));
 9       objectFactoryElement(root.evalNode("objectFactory"));
10       objectWrapperFactoryElement(root.evalNode("objectWrapperFactory"));
11       reflectorFactoryElement(root.evalNode("reflectorFactory"));
12       settingsElement(settings);
13       // read it after objectFactory and objectWrapperFactory issue #631
14       environmentsElement(root.evalNode("environments"));
15       databaseIdProviderElement(root.evalNode("databaseIdProvider"));
16       typeHandlerElement(root.evalNode("typeHandlers"));
17       mapperElement(root.evalNode("mappers"));
18     } catch (Exception e) {
19       throw new BuilderException("Error parsing SQL Mapper Configuration. Cause: " + e, e);
20     }
21   }

首先是配置文件加载properties类型的配置 propertiesElement(root.evalNode("properties"));

对应的mybatis配置文件为      

1  <properties resource="db.properties">
2      </properties>

等价于 

1 <properties url="file:///D:workspaceideagitdemo_01srcmain
esourcesdb.properties">
2 </properties>

两种写法均可以在其中<properties> 标签下可以添加<property>键值对

写法:

1 <property name="driver" value="com.mysql.cj.jdbc.Driver"/>

针对 propertiesElement(root.evalNode("properties"));方法分析为

 1 private void propertiesElement(XNode context) throws Exception {
 2   //判断mybatis配置文件是否有properties节点
 3     if (context != null) {
 4        //properties节点下的节点,即对应的键值对 
 5       Properties defaults = context.getChildrenAsProperties();
 6       //获取对应resource的值,对应这个例子为 db.properties
 7       String resource = context.getStringAttribute("resource");
 8       //在properties节点中也可以根据src获取配置文件,需要使用配置文件绝对路径
 9       String url = context.getStringAttribute("url");
10       if (resource != null && url != null) {
11         throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference.  Please specify one or the other.");
12       }
13       //将对应配置文件中的属性放到Properties类中
14       if (resource != null) {
15         defaults.putAll(Resources.getResourceAsProperties(resource));
16       } else if (url != null) {
17         defaults.putAll(Resources.getUrlAsProperties(url));
18       }
19       //获取Configuration配置,放入到 Properties 对象中
20       Properties vars = configuration.getVariables();
21       if (vars != null) {
22         defaults.putAll(vars);
23       }
24       //将Properties 对象赋值于xml路径解析中
25       parser.setVariables(defaults);
26       //将Properties 对象赋值于全局配置Configuration文件中
27       configuration.setVariables(defaults);
28     }
29   }
生于忧患,死于安乐
原文地址:https://www.cnblogs.com/songlove/p/14597393.html