在上一篇文章Mybatis:Mapper接口編程原理分析(二)中章贞,已經(jīng)知道 mapper 接口是怎么注冊(cè)的了,那么現(xiàn)在就是需要獲取 mapper 接口的代理了闺魏。
在使用 Mybatis 時(shí)未状,我們都是通過(guò)如下代碼去獲取 mapper 接口的代理的:
sqlSession.getMapper(UserMapper.class)
代碼只有一行,就獲取了 mapper 接口的代理對(duì)象了析桥,那么在內(nèi)部是怎么一回事呢司草?
- DefaultSqlSession
public <T> T getMapper(Class<T> type) {
// 從 Configuration 獲取 mapper 接口代理
return this.configuration.getMapper(type, this);
}
- Configuration
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
// 從 MapperRegistry 獲取 mapper 接口代理
return this.mapperRegistry.getMapper(type, sqlSession);
}
- MapperRegistry
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
// 獲取 mapper 接口的代理工廠
MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory)this.knownMappers.get(type);
if (mapperProxyFactory == null) {
throw new BindingException("Type " + type + " is not known to the MapperRegistry.");
} else {
try {
// 生成 mapper 代理
return mapperProxyFactory.newInstance(sqlSession);
} catch (Exception var5) {
throw new BindingException("Error getting mapper instance. Cause: " + var5, var5);
}
}
}
- MapperProxyFactory
public T newInstance(SqlSession sqlSession) {
// MapperProxy 實(shí)現(xiàn)了 InvocationHandler
MapperProxy<T> mapperProxy = new MapperProxy(sqlSession, this.mapperInterface, this.methodCache);
// 獲取 mapper 代理
return this.newInstance(mapperProxy);
}
// 生成 mapper 代理對(duì)象
protected T newInstance(MapperProxy<T> mapperProxy) {
return Proxy.newProxyInstance(this.mapperInterface.getClassLoader(), new Class[]{this.mapperInterface}, mapperProxy);
}
序列圖如下:
獲取 mapper 代理