您的位置:首页 > 编程语言 > Java开发

JAVA JDK 动态代理以及Mybatis的理解

2016-06-20 14:11 489 查看
AspectJASMCgLibjavassistJAVA JDK Proxy一.JAVA JDK Proxy是一个以实现接口动态创建类的API。在使用java proxy创建及实例化类时,至少实例化两个类,一个是由JVM自动实例化的类,一个是InvocationHandler,至于是否实例化要被代理的类,要看需要。MyBatis只实例化前两个类,MyBatis并不需要真的代理其他类。如:1.这是一个接口:
@Mapper
public interface CRMGateWayRequestInfoMapper {
List<GatewayRequestInfo> queryRequestSerialNo(Map<String,Object> param);

int countByCond(Map<String,Object> param);
}
2.MyBatis通过代理实现这个接口:
1)InvocationHandler
public class MapperProxy<T> implements InvocationHandler, Serializable {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (Object.class.equals(method.getDeclaringClass())) {
try {
return method.invoke(this, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
final MapperMethod mapperMethod = cachedMapperMethod(method);
return mapperMethod.execute(sqlSession, args);
}
}2)Proxy.newProxyInstance
public class MapperProxyFactory<T> {
@SuppressWarnings("unchecked")
protected T newInstance(MapperProxy<T> mapperProxy) {
return (T) Proxy.newProxyInstance(mapperInterface.getClassLoader(), new Class[] { mapperInterface }, mapperProxy);
}
}
从上面的代码可以看出MyBatis并没有代理实际的类(invoke方法中执行的是mapperMethod.execute)。
这个例子加深了我对JAVA Proxy的概念理解。Proxy是一个由JVM自动创建的类对象,它实现了传递的接口。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: