Mybatis源码解析-加载配置文件properties节点

87 阅读1分钟

Configuration文件是Mybatis的全局核心文件,加载了datasource ,mapper,TypeHandler等

上一篇介绍了加载Configuration的主流程代码,Mybatis配置初始化Configuration

今天开始选择核心部分逐个介绍,下面先看配置文件 mybatis-config.xml

mybatis-config.xml

前文提到这里解析properties

解析配置文件核心流程

解析属性节点,支持resource 或 url的方式引入文件,同时支持单独配置,解析过程如下看注释。

private void propertiesElement(XNode context) throws Exception {
  if (context != null) {
    Properties defaults = context.getChildrenAsProperties();
    //如果有resource 或 url  注意这里不能同时配置
    String resource = context.getStringAttribute("resource");
    String url = context.getStringAttribute("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.");
    }
    if (resource != null) {
      defaults.putAll(Resources.getResourceAsProperties(resource));
    } else if (url != null) {
      defaults.putAll(Resources.getUrlAsProperties(url));
    }
    //获取节点的properties,
    Properties vars = configuration.getVariables();
    if (vars != null) {
      defaults.putAll(vars);
    }
    //存到parser里面,因为后面如果有变量占位符会使用到
    parser.setVariables(defaults);
    //存到configuration的properties变量里
    configuration.setVariables(defaults);
  }
}

Resources是IO模块下的类,负责读取各种资源文件,先

看下Resources读取的源码Resources.getResourceAsProperties

  public static Properties getResourceAsProperties(String resource) throws IOException {
    Properties props = new Properties();
//    resource 处理成输入流
    try (InputStream in = getResourceAsStream(resource)) {
      props.load(in);
    }
    return props;
  }

然后 Properties的load方法。这就是JDK里面的方法,大家可以自己看看