1. 程式人生 > >mybatis源碼閱讀(三)

mybatis源碼閱讀(三)

ror 代理 nal urn 源碼 erp n) mybatis clas

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); }

答案:動態代理

mybatis源碼閱讀(三)