Mybatis是如何通过动态代理实现mapping 接口实现类的.
利用动态代理实现mapping 实现类主要有三个类, MapperRegistry,MapperProxy,MapperProxyFactory
详情:
类名: MapperRegistry
说明: 映射注册. 初始化MapperProxyFactory类,并将接口与对应的MapperProxyFactory,注册到Configuration类.
类名: MapperProxy
说明: 映射代理类. 实现了InvocationHandler接口. 代理类创建所需的类. 在这个类中就可以添加需要的业务逻辑.代理类会在被 调用时执行业务逻辑.
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
try {
if (Object.class.equals(method.getDeclaringClass())) {
return method.invoke(this, args);
} else if (isDefaultMethod(method)) {
return invokeDefaultMethod(proxy, method, args);
}
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
这个类动态实现了mapping接口.达到只需要调用mapping接口中的方法,就可以完成数据库操作.
类名: MapperProxyFactory
说明: 映射代理工程类,用于生产Mapping接口动态代理类的类.这个类不直接创建动态代理类,只提供生产代理类的方法.
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}