JAVA JDK 動態代理以及Mybatis的理解

AspectJ

ASM

CgLib

javassist

JAVA 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自動創建的類對象,它實現了傳遞的接口。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章