MyBatis中Mapper的产生源码分析

调用getMapper方法

SqlSession#getMapper->(DefaultSqlSession)configuration#getMapper–>(Configuration)mapperRegistry#getMapper

//MapperRegistry类
@SuppressWarnings("unchecked")
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null) {
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    }
    try {
       //调用工厂方法
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
//MapperProxyFactroy类
@SuppressWarnings("unchecked")
//这里即产生一个mapper接口的代理对象 代理对象的调用在下面类中体现
  protected T newInstance(MapperProxy<T> mapperProxy) {
      //参数分别为Mapper接口的类加载器、mapper接口、对应的invocationHandler
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
//MapperRegistry调用的是这个方法 这个方法又调用上面产生代理对象的方法
  public T newInstance(SqlSession sqlSession) {
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
//MapperProxy类
@Override
  public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    try {
        //如果该方法是Object中的基本方法 则调用这个循环代码
      if (Object.class.equals(method.getDeclaringClass())) {
        return method.invoke(this, args);
      } else if (isDefaultMethod(method)) {
          //如果接口方法是被Default修饰符修饰 则调用这个循环代码
        return invokeDefaultMethod(proxy, method, args);
      }
    } catch (Throwable t) {
      throw ExceptionUtil.unwrapThrowable(t);
    }
      //否则该方法即是Mapper中声明的方法 即调用SqlSession来执行
    final MapperMethod mapperMethod = cachedMapperMethod(method);
    return mapperMethod.execute(sqlSession, args);
  }

综上可以看出Mapper是基于动态代理产生出来的。

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