mybatis源码分析 ---- Properties节点解析

解析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);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值