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是基於動態代理產生出來的。

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