Mybatis Mapper 接口工作原理 2 - 获取 mapper 代理对象
sqlSession.getMapper() 获取到的是 Mapper 接口的代理对象。这个代理对象是由 MyBatis 通过 JDK 动态代理 生成的,核心类是 MapperProxy。
1 sqlSession.getMapper() 的源码分析
sqlSession.getMapper() 是 SqlSession 接口的方法,其默认实现位于 DefaultSqlSession 中:
@Override
public <T> T getMapper(Class<T> type) {
return configuration.getMapper(type, this);
}
configuration.getMapper():调用Configuration对象的getMapper方法。
2 Configuration.getMapper() 的源码分析
Configuration 是 MyBatis 的核心配置类,getMapper 方法的实现如下:
public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
return mapperRegistry.getMapper(type, sqlSession);
}
mapperRegistry.getMapper():调用MapperRegistry的getMapper方法。
3 MapperRegistry.getMapper() 的源码分析
MapperRegistry 是 MyBatis 中用于管理 Mapper 接口的注册中心,getMapper 方法的实现如下:
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);
}
}
knownMappers:是一个Map<Class<?>, MapperProxyFactory<?>>,存储了所有注册的 Mapper 接口和对应的MapperProxyFactory。mapperProxyFactory.newInstance(sqlSession):通过MapperProxyFactory创建 Mapper 接口的代理对象。
4 MapperProxyFactory.newInstance() 的源码分析
MapperProxyFactory 是用于创建 Mapper 接口代理对象的工厂类,newInstance 方法的实现如下:
public class MapperProxyFactory<T> {
private final Class<T> mapperInterface;
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
public T newInstance(SqlSession sqlSession) {
final MapperProxy<T> mapperProxy = new MapperProxy<>(sqlSession, mapperInterface);
return newInstance(mapperProxy);
}
}
Proxy.newProxyInstance():使用 JDK 动态代理创建 Mapper 接口的代理对象。MapperProxy:是InvocationHandler的实现类,负责拦截 Mapper 接口的方法调用。
总结
sqlSession.getMapper() 获取到的是 Mapper 接口的代理对象,这个代理对象是通过 JDK 动态代理生成的,核心类是 MapperProxy。

浙公网安备 33010602011771号