<properties>
标签读取#propertiesElement(XNode context)
方法,解析 <properties />
节点。大致逻辑以下:java
解析 <properties />
标签,成Properties对象。覆盖configuration中的 Properties 对象到上面的结果。设置结果到 parser 和configuration 中。代码以下:apache
//xxxx.properties
prop1=bbbb
//mybatis-config
<properties resource="org/apache/ibatis/builder/jdbc.properties">
<property name="prop1" value="aaaa"/>
</properties>
Properties props = new Properties();
props.put("prop1", "cccc");
XMLConfigBuilder builder = new XMLConfigBuilder(inputStream, null, props);
复制代码
// XMLConfigBuilder.java
private void propertiesElement(XNode context) throws Exception {
if (context != null) {
// 读取子标签们,为 Properties 对象
Properties defaults = context.getChildrenAsProperties();
// 读取 resource 和 url 属性
String resource = context.getStringAttribute("resource");
String url = context.getStringAttribute("url");
if (resource != null && url != null) { // resource 和 url 都存在的状况下,抛出 BuilderException 异常
throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference. Please specify one or the other.");
}
// 读取本地 Properties 配置文件到 defaults 中。
if (resource != null) {
defaults.putAll(Resources.getResourceAsProperties(resource));
// 读取远程 Properties 配置文件到 defaults 中。
} else if (url != null) {
defaults.putAll(Resources.getUrlAsProperties(url));
}
// 读取 configuration 中的 Properties 对象到 defaults 中。
Properties vars = configuration.getVariables();
if (vars != null) {
defaults.putAll(vars);
}
// 设置 defaults 到 parser 和 configuration 中。
parser.setVariables(defaults);
configuration.setVariables(defaults);
}
}
复制代码
若是属性在不仅一个地方进行了配置,那么 MyBatis 将按照下面的顺序来加载:bash
所以,经过方法参数传递的属性具备最高优先级,resource/url 属性中指定的配置文件次之,最低优先级的是 properties 属性中指定的属性。mybatis
失控的阿甘,乐于分享,记录点滴ui