Mybatis源碼分析(03)-配置文件解析-mappers標籤四種配置方式的處理

mappers標籤四種配置方式

上一篇中提到XMLConfigBuilder.mapperElement()方法,該方法用於對核心配置文件中<mappers>標籤的解析,先回顧一下<mappers>標籤中,對於mapper接口或映射文件的幾種引入方式:

<!-- 方式1:使用包名引入,通過name屬性指定mapper接口所在的包名,要求映射配置文件必須和接口同包同名 -->
<mappers>
  <package name="com.mybatisTest.mapper"/>
</mappers>
<!-- 方式2:使用接口類引入,通過class屬性指定mapper接口,要求映射配置文件必須和接口同包同名 -->
<mappers>
  <mapper class="com.mybatisTest.mapper.accountMapper"/>
</mappers>
<!-- 方式3:使用本地文件路徑引入,通過url指定映射配置文件的本地文件路徑-->
<mappers>
  <mapper url="file:///var/mappers/accountMapper.xml"/>
</mappers>
<!-- 方式4:使用類路徑引入,通過resource屬性指定映射配置文件在classpath下的路徑-->
<mappers>
  <mapper resource="com.mybatisTest.mapper.accountMapper.xml"/>
</mappers>

源碼分析

回到mapperElement()方法,可以看出對映射文件不同引入方式的解析

private void mapperElement(XNode parent) throws Exception {
  if (parent != null) {
    for (XNode child : parent.getChildren()) {
      //使用包名引入
      if ("package".equals(child.getName())) {
        String mapperPackage = child.getStringAttribute("name");
        configuration.addMappers(mapperPackage);
      } else {
        String resource = child.getStringAttribute("resource");
        String url = child.getStringAttribute("url");
        String mapperClass = child.getStringAttribute("class");
        //使用類路徑引入
        if (resource != null && url == null && mapperClass == null) {
          ErrorContext.instance().resource(resource);
          InputStream inputStream = Resources.getResourceAsStream(resource);
          XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource, configuration.getSqlFragments());
          mapperParser.parse();
          //使用本地文件路徑引入
        } else if (resource == null && url != null && mapperClass == null) {
          ErrorContext.instance().resource(url);
          InputStream inputStream = Resources.getUrlAsStream(url);
          XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url, configuration.getSqlFragments());
          mapperParser.parse();
          //使用接口類引入
        } else if (resource == null && url == null && mapperClass != null) {
          Class<?> mapperInterface = Resources.classForName(mapperClass);
          configuration.addMapper(mapperInterface);
        } else {
          throw new BuilderException("A mapper element may only specify a url, resource or class, but not more than one.");
        }
      }
    }
  }
}

如果使用類路徑或本地文件路徑引入,mybatis會先註冊接口,然後並且解析xml,掃描接口中的註解,時序圖如下:

在這裏插入圖片描述

使用類路徑或本地文件路徑引入,會先調用XMLMapperBuilder.parse()方法:

public void parse() {
  //判斷是否已經加載過該映射配置文件
  if (!configuration.isResourceLoaded(resource)) {
    //從根節點<mapper>開始解析
    configurationElement(parser.evalNode("/mapper"));
    //將映射配置文件添加到loadedResources集合中,該集合記錄了已經加載的映射配置文件
    configuration.addLoadedResource(resource);
    //註冊Mapper接口
    bindMapperForNamespace();
  }
  // 處理configurationElement()方法中解析失敗的<resultMap>節點
  parsePendingResultMaps();
  // 處理configurationElement()方法中解析失敗的<cache-ref>節點
  parsePendingCacheRefs();
  // 處理configurationElement()方法中解析失敗的SQL語句節點
  parsePendingStatements();
}

而在bindMapperForNamespace()會調用configuration.addMapper(),完成mapper接口的註冊,以及接口中註解的解析:

private void bindMapperForNamespace() {
  //獲取映射配置文件的命名空間
  String namespace = builderAssistant.getCurrentNamespace();
  if (namespace != null) {
    Class<?> boundType = null;
    try {
      //通過反射得到namespace對應的Class對象
      boundType = Resources.classForName(namespace);
    } catch (ClassNotFoundException e) {
      //ignore, bound type is not required
    }
    if (boundType != null) {
      if (!configuration.hasMapper(boundType)) {  //是否已經註冊boundType接口
        // Spring may not know the real resource name so we set a flag
        // to prevent loading again this resource from the mapper interface
        // look at MapperAnnotationBuilder#loadXmlResource
        configuration.addLoadedResource("namespace:" + namespace); //記錄namespace
        configuration.addMapper(boundType); //調用MapperRegistry.addMapper()方法,註冊boundType接口
      }
    }
  }
}

如果使用包名或接口類引入,mybatis會先解析xml,然後再去註冊接口,掃描接口中的註解,時序圖如下:

在這裏插入圖片描述

先調用configuration.addMapper()方法

public <T> void addMapper(Class<T> type) {
  if (type.isInterface()) {
    if (hasMapper(type)) { //已經註冊,拋出異常
      throw new BindingException("Type " + type + " is already known to the MapperRegistry.");
    }
    boolean loadCompleted = false;
    try {
      knownMappers.put(type, new MapperProxyFactory<>(type));  //完成註冊
      // It's important that the type is added before the parser is run
      // otherwise the binding may automatically be attempted by the
      // mapper parser. If the type is already known, it won't try.
      MapperAnnotationBuilder parser = new MapperAnnotationBuilder(config, type);
      parser.parse();  //解析接口文件中的註解,以及對應的映射配置文件
      loadCompleted = true;
    } finally {
      if (!loadCompleted) {
        knownMappers.remove(type);
      }
    }
  }
}

然後,會調用MapperAnnotationBuilder.parse()方法,該方法內部會進行映射配置文件的解析,以及註解的解析:

public void parse() {
  String resource = type.toString();
  if (!configuration.isResourceLoaded(resource)) {
    //加載與這個接口相關聯的xml文件
    loadXmlResource();
    configuration.addLoadedResource(resource);
    assistant.setCurrentNamespace(type.getName());
    parseCache();
    parseCacheRef();
    Method[] methods = type.getMethods();
    for (Method method : methods) {
      try {
        // issue #237
        if (!method.isBridge()) {
          parseStatement(method); //解析註解形式的statement
        }
      } catch (IncompleteElementException e) {
        configuration.addIncompleteMethod(new MethodResolver(this, method));
      }
    }
  }
  parsePendingMethods();
}

在loadXmlResource()方法中,又會調用XMLMapperBuilder.parse()方法進行映射配置文件的解析

從這個方法可以看出,映射配置文件是通過 type.getName(),也就是接口的全類名找到的,這也就是爲什麼使用包名或接口類引入mapper接口,要求映射配置文件必須與接口同包同名了

private void loadXmlResource() {
  // Spring may not know the real resource name so we check a flag
  // to prevent loading again a resource twice
  // this flag is set at XMLMapperBuilder#bindMapperForNamespace
  //XMLMapperBuilder.bindMapperForNamespace()方法中的
  // 使用configuration.addLoadedResource("namespace:" + namespace)標記namespace之後
  //就不會再進行xml解析了
  if (!configuration.isResourceLoaded("namespace:" + type.getName())) {
    String xmlResource = type.getName().replace('.', '/') + ".xml";
    // #1347
    InputStream inputStream = type.getResourceAsStream("/" + xmlResource);
    if (inputStream == null) {
      // Search XML mapper that is not in the module but in the classpath.
      try {
        inputStream = Resources.getResourceAsStream(type.getClassLoader(), xmlResource);
      } catch (IOException e2) {
        // ignore, resource is not required
      }
    }
    if (inputStream != null) {
      XMLMapperBuilder xmlParser = new XMLMapperBuilder(inputStream, assistant.getConfiguration(), xmlResource, configuration.getSqlFragments(), type.getName());
      xmlParser.parse();
    }
  }
}

總結:在使用mappers標籤,用包名和接口類引入mapper接口時,調用的順序是configuration.addMapper()->XMLMapperBuilder.parse(),而使用本地文件路徑和類路徑引入映射配置文件時,調用的順序是XMLMapperBuilder.parse()->configuration.addMapper(),當然爲了避免不斷地循環調用下去,會利用configuration.addLoadedResource()和configuration.isResourceLoaded()去設置和判斷flag。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章