Mybatis 代码流程及实现原理解析(二)

XMLConfigBuilder.java中

1. propertiesElement(root.evalNode("properties")); 此方法解析<properties>及其子节点。

代码实现:

private void propertiesElement(XNode context) throws Exception {
    if (context != null) {
      Properties defaults = context.getChildrenAsProperties();//解析所有子节点property 值
      String resource = context.getStringAttribute("resource");
      String url = context.getStringAttribute("url");
      if (resource != null && url != null) { //从外部引入property文件
        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 vars = configuration.getVariables();
      if (vars != null) {
        defaults.putAll(vars);
      }
      parser.setVariables(defaults);  //这里要将property给parser,因为在后面的一些可以能会用到这些属性值。
      configuration.setVariables(defaults);
    }
  }
xml 节点样例:

<properties resource="org/mybatis/example/config.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties>
从代码可以看出:

1.先把解析子节点property 值, 然后再把外部引入进来的property信息添加到已有的properties中。

2. 支持以resource 和url的方式引入外部的property,但是两者只能有其中之一。

3,节点解析完以后,放入configuration类中。<properties>在这个类中的存在形式是:

protected Properties variables = new Properties();

2.typeAliasesElement(root.evalNode("typeAliases")); 此方法解析<typeAliases>及其子节点。

private void typeAliasesElement(XNode parent) {
    if (parent != null) {
      for (XNode child : parent.getChildren()) {
        if ("package".equals(child.getName())) {
          String typeAliasPackage = child.getStringAttribute("name");
          configuration.getTypeAliasRegistry().registerAliases(typeAliasPackage);//将整个包下的类添加的别名集合中。
        } else {
          String alias = child.getStringAttribute("alias");
          String type = child.getStringAttribute("type");
          try {
            Class<?> clazz = Resources.classForName(type);
            if (alias == null) {
              typeAliasRegistry.registerAlias(clazz); //如果alias 不存在,则回去检查是否有Alias的annotation,有的话用annotation的值,没有则用type的简单类/              //名
            } else {
              typeAliasRegistry.registerAlias(alias, clazz);
            }
          } catch (ClassNotFoundException e) {
            throw new BuilderException("Error registering typeAlias for '" + alias + "'. Cause: " + e, e);
          }
        }
      }
    }
  }

xml 节点样例:

<typeAliases>
  <typeAlias alias="Author" type="domain.blog.Author"/>
  <package name="domain.blog"/>
</typeAliases>

从代码可以看出:

1. 如果有<package>子节点, 则将整个包中的类放入到别名集合中。

2. 如果是<typeAlias>子节点, 则直接放入到别名集合中。

3. 放入别名集合的原则是:如果alias 不存在,则回去检查是否有Alias的annotation,有的话用annotation的值,没有则把type的简单类名当做alias。 并且alias所代表的type不能有重复。 相关实现可以参考类TypeAliasRegistry.java


3. pluginElement,objectFactoryElement,objectWrapperFactoryElement,settingsElement,environmentsElement,databaseIdProviderElement,typeHandlerElement 就不一个一个分析, 都是去解析相关节点,然后放入Configuration.java 这个类中。


4. mapperElement(root.evalNode("mappers")); 此方法解析<mappers>及其子节点。

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.");
          }
        }
      }
    }
  }

xml 节点样例 

<mappers>
        <mapper resource="com/skoyou/mapper/User.xml"/>
        <mapper url="file:///var/mappers/AuthorMapper.xml"/>
        <mapper class="org.mybatis.builder.AuthorMapper"/>
        <package name="org.mybatis.builder"/>
</mappers>

从代码可以看出:

1. 当前支持四种方式来加载mapper内容: resource,url,class,package。

   class方式直接把class的类类型加入到configuration类的相关mapper变量中。这个变量就是MapperRegistry.java

   package方式会多一个操作就是找出该package(包含子包)下的类。

  看addmapper的实现:具体在MapperRegistry.java中。

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<T>(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);
        }
      }
    }
  }
实际上 mapper类型只能是接口,且不能重复加入。 由于package和class的方式是直接引入mapper接口,具体的sql或mapper文件是通过注解的方式加入到这个接口的。所以addMapper方法还会进行一些额外的解析。 具体在此方法的中调用的MapperAnnotationBuilder的parse()方法。
  public void parse() {
    String resource = type.toString();
    if (!configuration.isResourceLoaded(resource)) {
      loadXmlResource(); //尝试加载同名的mapper文件,没有的话就不处理
      configuration.addLoadedResource(resource);
      assistant.setCurrentNamespace(type.getName());
      parseCache();
      parseCacheRef();
      Method[] methods = type.getMethods();
      for (Method method : methods) {
        try {
          parseStatement(method); //主要是看方法上面有没有相关注解(@select,@update等)
        } catch (IncompleteElementException e) {
          configuration.addIncompleteMethod(new MethodResolver(this, method));
        }
      }
    }
    parsePendingMethods();
  }



  url,resource方式是从外部引入新的mapper文件, 对外部文件解析之后再将转换后的内容加入到configuration中。

看XMLMapperBuilder.parse()方法:

public void parse() {
    if (!configuration.isResourceLoaded(resource)) {
      configurationElement(parser.evalNode("/mapper"));// 具体解析mapper文件
      configuration.addLoadedResource(resource);
      bindMapperForNamespace();
    }

    parsePendingResultMaps();
    parsePendingChacheRefs();
    parsePendingStatements();
  }

下篇会具体看看configurationElement() 这个方法, 因为mapper文件的各节点解析都在这个文件中。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值