解析Properties节点
Properties节点用来引入外部文件,或者存储一些配置的值。在后面可以通过${name}的值直接使用
<!--<properties resource=""></properties>-->
<!--<properties url=""></properties>-->
<properties resource="db.properties">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis"/>
<property name="username" value="root"/>
<property name="password" value="like12345"/>
</properties>
其有两个属性,分别是url,resource,两个值不能共存。否则会抛出异常。在解析的过程中优先解析子节点,再解析属性,最终将解析的值存入configuration对象的properties属性中。因此会存在同名覆盖的情况。即外部文件的值会覆盖子节点中的值。
/**
* 解析properties标签
* @param context <properties> .... </properties>
* @throws Exception
*/
private void propertiesElement(XNode context) throws Exception {
if (context != null) {
// 1、解析子节点 <property></property>
Properties defaults = context.getChildrenAsProperties();
// 2、获取resource和url属性的值
String resource = context.getStringAttribute("resource");
String url = context.getStringAttribute("url");
/*resource和url有且仅能有一个*/
if (resource != null && url != null) {
throw new BuilderException("The properties element cannot specify both a URL and a resource based property file reference. Please specify one or the other.");
}
/* 从文件系统或者URL中读到的值会对子节点中设置的值进行覆盖 */
if (resource != null) {
defaults.putAll(Resources.getResourceAsProperties(resource));
} else if (url != null) {
defaults.putAll(Resources.getUrlAsProperties(url));
}
Properties vars = configuration.getVariables();
if (vars != null) {
defaults.putAll(vars);
}
parser.setVariables(defaults);
/* 将值设置到Configurtion的properties属性中 */
configuration.setVariables(defaults);
}
}