『手撕 Mybatis 源码』07 - Proxy 对象创建

Proxy 对象创建

  1. 问题
  • sqlSession.getMapper(UserMapper.class) 是如何生成的代理对象?
  1. Mapper 代理方式初始化完成后,下一步进行获取代理对象来执行
public class MybatisTest {
  /**
   * 问题2:sqlSession.getMapper(UserMapper.class); 是如何生成的代理对象?
   * 解答:(T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
   *       使用的就是 JDK 动态代理
  **/
  @Test
  public void test2() throws IOException {
    ...
    // 1. JDK 动态代理生成代理对象,就是这里
    UserMapper mapperProxy = sqlSession.getMapper(UserMapper.class);
    ...
  }
}
  1. 当调用 getMapper() 时,DefaultSqlSession 实际会委托 Configuration 来获取 Mapper 代理对象
public class DefaultSqlSession implements SqlSession {
  
  private final Configuration configuration;
  ...
  @Override
  public <T> T getMapper(Class<T> type) {
    // 从 Configuration 对象中,根据 Mapper 接口,获取 Mapper 代理对象
    return configuration.getMapper(type, this);
  }
}
  1. Configuration 对象又会通过 MapperRegistry 获取 Mapper 代理对象
public class Configuration {
  
  protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
  ...
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
}
  1. MapperRegistry 中,会通过 knownMappers 获取 Mapper 代理对象工厂,然后通过 Mapper 代理对象工厂生成 Mapper 代理对象
public class MapperRegistry {

  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();
  ...
  public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    // 1. 根据 Mapper 接口的类型,从 Map 集合中获取 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 { 
      // 2. 通过 MapperProxyFactory 生产 MapperProxy,通过 MapperProxy 产生 Mapper 代理对象
      return mapperProxyFactory.newInstance(sqlSession);
    } catch (Exception e) {
      throw new BindingException("Error getting mapper instance. Cause: " + e, e);
    }
  }
}
  1. MapperProxyFactory 会创建MapperProxy 对象,封装相应参数,然后使用 JDK 动态代理方式,生成代理对象
public class MapperProxyFactory<T> {

  private final Class<T> mapperInterface;
  private final Map<Method, MapperMethodInvoker> methodCache = new ConcurrentHashMap<>();
  ...
  @SuppressWarnings("unchecked")
  protected T newInstance(MapperProxy<T> mapperProxy) {
    // 2. 使用 JDK 动态代理方式,生成代理对象
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }

  public T newInstance(SqlSession sqlSession) {
    // 1. InvocationHandler 接口的实现类
    final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface, methodCache);
    return newInstance(mapperProxy);
  }
}
  1. 总结
    『手撕 Mybatis 源码』07 - Proxy 对象创建_第1张图片

你可能感兴趣的:(『数据库』,mybatis,java,开发语言)