Mybatis源码解析(2) 获取 MapperProxy 代理对象

1 获取代理对象
上一篇已经讲述了配置文件加载到 configuration 对象中,并创建了 SqlSessionFactory 对象,此处省略了 SqlSession 对象的获取,直接看获取代理对象的源码过程
//从sqlSession中获取代理对象
UserMapper mapper = sqlSession.getMapper(UserMapper.class);

2 封装的获取代理对象方法
  • 类 : DefaultSqlSession
  • 方法 : getMapper()
  • 作用 : 从创建好的 configuration 对象中拿取代理对象
public class DefaultSqlSession implements SqlSession {
  //配置对象
  private Configuration configuration;
  //执行器
  private Executor executor;
  //是否开启自动提交
  private boolean autoCommit;
  private boolean dirty;
  private List<Cursor<?>> cursorList;
//获取代理对象方法
public <T> T getMapper(Class<T> type) {
    return configuration.<T>getMapper(type, this);
  }
3 接着点进去
  • 类 : Configuration
  • 方法 : getMapper()
  • 作用 : 实质是从映射注册表对象中获取已经创建好的代理对象,创建代理对象的过程在加载接口时完成
public class Configuration {
  //映射注册表,该集合中存储了接口与代理对象的映射
  protected final MapperRegistry mapperRegistry = new MapperRegistry(this);
  
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
    return mapperRegistry.getMapper(type, sqlSession);
  }
4 查看具体获取方法
  • 类 : MapperRegistry 映射注册表
  • 方法 : getMapper()
  • 作用 : 该类在加载接口时为其创建代理对象并放入集合中,便于后期调用,起到缓存的作用
public class MapperRegistry {
  //配置对象
  private final Configuration config;
  //接口与代理工厂的映射关系
  private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<Class<?>, MapperProxyFactory<?>>();
//获取代理对象过程
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);
    }
  }
5 进入工厂类中,查看生产代理实例的过程
  • 类 : MapperProxyFactory
  • 方法 : newInstance()
  • 作用 : 代理工厂类,生产代理实例 MapperProxy对象 的过程
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) {
	//生产代理实例API	(被代理类加载器,被代理类的接口,实现invocationHandler接口类)
    return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
  }
总结 :
该过程完成了获取代理接口的作用, 实质是从 MapperRegistry 接口注册表类中根据接口类型获取该接口的代理工厂类,之后再创建代理实例返回
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值