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

来源:互联网 发布:因子分解机 推荐算法 编辑:程序博客网 时间:2024/06/11 19:50

AspectJ

ASM

CgLib

javassist

JAVA JDK Proxy


一.JAVA JDK Proxy是一个以实现接口动态创建类的API。在使用java proxy创建及实例化类时,至少实例化两个类,一个是由JVM自动实例化的类,一个是InvocationHandler,至于是否实例化要被代理的类,要看需要。MyBatis只实例化前两个类,MyBatis并不需要真的代理其他类。

如:

1.这是一个接口:

@Mapperpublic 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 {
@Overridepublic 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自动创建的类对象,它实现了传递的接口。


0 0
原创粉丝点击