Configuration--properties(三-1)

上一篇文章我们看到了parseConfiguration方法,这个方法逐个解析configuration下面的子标签.本篇文章我们我们来看properties标签的作用.

首先我们来看一下properties标签的作用,properties主要的作用就是动态的配置一些key-value的属性值,可以直接在properties的子标签property中配置,也可以从.properties文件中获取.

<properties resource="org/mybatis/example/config.properties">
  <property name="username" value="root"/>
  <property name="password" value="password"/>
</properties>

现在就让我们来看看propertiesElement(root.evalNode(“properties”));方法里到底做了什么:

  private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      // 将properties标签下所有property标签定义的值转换成一个Properties(该类继承Hashtable)对象
      Properties defaults = context.getChildrenAsProperties();

      String resource = context.getStringAttribute("resource");
      String url = context.getStringAttribute("url");
      // properties标签的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.");

      // 将.properties文件中定义的各中值,加入到defaults.从这里我们可以看出,.properties文件中若定义了和property标签中key值一样的参数,最终会以.properties文件中的值为准,因为这里会覆盖之前的值
      if (resource != null) {
        defaults.putAll(Resources.getResourceAsProperties(resource));
      } else if (url != null) {
        defaults.putAll(Resources.getUrlAsProperties(url));
      }

      // 这里的值,是Configuration类中本身的参数,大家可以去上一章XMLConfigBuilder的构造方法,其中调用了this.configuration.setVariables(props),而这个里面的props参数其实是SqlSessionFactoryBuilder的build方法中传来的.
      // 从这里我们得知,我们在代码中构造SqlSessionFactory时调用SqlSessionFactoryBuilder.build方法时,也可以传入一个Properties,并且在这里传入的参数,优先级最高,可以覆盖property标签和.properties文件中key相同的参数.
      // 不过如果在代码中传入Properties就失去了配置文件的灵活性,不过也可以用这种方法来限制一些不可以被修改的参数值.
      Properties vars = configuration.getVariables();
      if (vars != null) {
        defaults.putAll(vars);
      }

      // parser是XMLConfigBuilder中真正去解析xml文件的类XPathParser,这里将这些参数设置进去,我猜测应该是之后解析其他标签时会用上,因为在environments标签下的dataSource中,我们还会使用${}这种形式来定义一个值的value
      parser.setVariables(defaults);

      // 将最终的key-value参数值设置进Configuration的variables属性中
      configuration.setVariables(defaults);
    }
  }

XNode类:

  public Properties getChildrenAsProperties() {
    Properties properties = new Properties();
    for (XNode child : getChildren()) {
      String name = child.getStringAttribute("name");
      String value = child.getStringAttribute("value");
      if (name != null && value != null) {
        properties.setProperty(name, value);
      }
    }
    return properties;
  }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值