mybatis源码阅读(三)

SqlSesion怎么获取一个Mapper?

一个Mapper接口没有一个实现类怎么能够实例化?

public <T> T getMapper(Class<T> type) {
    // 通过 configuration 的getMapper方法获取Mapper对象
    return configuration.<T>getMapper(type, this);
  }

  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 通过MapperRegistry对象获取 Mapper的对象
    return mapperRegistry.getMapper(type, sqlSession);
  }

  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 通过注册的 mapperProxy 获取mapperProxyFactory 这里的knownMappers 在解析 mapper 的时候添加进入的
    final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
    if (mapperProxyFactory == null)
      throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
    try {
      // 通过mapperProxyFactory 实例化一个对象
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }

  public T newInstance(SqlSession sqlSession) {
    //MapperProxy 继承了 InvocationHandler
    final MapperProxy<T> mapperProxy = new MapperProxy<T>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }

  protected T newInstance(MapperProxy<T> mapperProxy) {
    // 动态代理的对像
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

答案:动态代理

猜你喜欢

转载自www.cnblogs.com/jas0/p/9545504.html