学习一下JavassistProxyFactory类,其实它跟CglibProxyFactory几乎是一样的用法
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import javassist.util.proxy.MethodHandler;
import javassist.util.proxy.Proxy;
import javassist.util.proxy.ProxyFactory;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.loader.AbstractEnhancedDeserializationProxy;
import org.apache.ibatis.executor.loader.AbstractSerialStateHolder;
import org.apache.ibatis.executor.loader.ResultLoaderMap;
import org.apache.ibatis.executor.loader.WriteReplaceInterface;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.apache.ibatis.reflection.ExceptionUtil;
import org.apache.ibatis.reflection.factory.ObjectFactory;
import org.apache.ibatis.reflection.property.PropertyCopier;
import org.apache.ibatis.reflection.property.PropertyNamer;
import org.apache.ibatis.session.Configuration;
/**JavassistProxy字节码生成代理
* 1.创建一个代理对象然后将目标对象的值赋值给代理对象,这个代理对象是可以实现其他的接口
* 2. JavassistProxyFactory实现ProxyFactory接口createProxy(创建代理对象的方法)
* @author Eduardo Macarron
*/
public class JavassistProxyFactory implements org.apache.ibatis.executor.loader.ProxyFactory {
/**
* finalize方法(垃圾回收)
*/
private static final String FINALIZE_METHOD = "finalize";
/**
* writeReplace(序列化写出方法)
*/
private static final String WRITE_REPLACE_METHOD = "writeReplace";
/**
* 加载ProxyFactory, 也就是JavassistProxy的入口
*/
public JavassistProxyFactory() {
try {
Resources.classForName("javassist.util.proxy.ProxyFactory");
} catch (Throwable e) {
throw new IllegalStateException("Cannot enable lazy loading because Javassist is not available. Add Javassist to your classpath.", e);
}
}
/**
* 创建代理
* @param target 目标对象
* @param lazyLoader 延迟加载Map集合(那些属性是需要延迟加载的)
* @param configuration 配置类
* @param objectFactory 对象工厂
* @param constructorArgTypes 构造函数类型[]
* @param constructorArgs 构造函数的值[]
* @return
*/
@Override
public Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
return EnhancedResultObjectProxyImpl.createProxy(target, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs);
}
public Object createDeserializationProxy(Object target, Map<String, ResultLoaderMap.LoadPair> unloadedProperties, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
return EnhancedDeserializationProxyImpl.createProxy(target, unloadedProperties, objectFactory, constructorArgTypes, constructorArgs);
}
@Override
public void setProperties(Properties properties) {
// Not Implemented
}
/**
* 获取代理对象, 也就是说在执行方法之前首先调用MethodHanlder的invoke方法
* @param type 目标类型
* @param callback 回调对象
* @param constructorArgTypes 构造函数类型数组
* @param constructorArgs 构造函数值的数组
* @return
*/
static Object crateProxy(Class<?> type, MethodHandler callback, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
// 创建一个代理工厂类
// 配置超类
ProxyFactory enhancer = new ProxyFactory();
enhancer.setSuperclass(type);
//判断是否有writeReplace方法,如果没有将这个代理对象实现WriteReplaceInterface接口,这个接口只有一个writeReplace方法
try {
type.getDeclaredMethod(WRITE_REPLACE_METHOD);
// ObjectOutputStream will call writeReplace of objects returned by writeReplace
if (LogHolder.log.isDebugEnabled()) {
LogHolder.log.debug(WRITE_REPLACE_METHOD + " method was found on bean " + type + ", make sure it returns this");
}
} catch (NoSuchMethodException e) {
enhancer.setInterfaces(new Class[]{WriteReplaceInterface.class});
} catch (SecurityException e) {
// nothing to do here
}
Object enhanced;
Class<?>[] typesArray = constructorArgTypes.toArray(new Class[constructorArgTypes.size()]);
Object[] valuesArray = constructorArgs.toArray(new Object[constructorArgs.size()]);
try {
// 根据构造函数创建一个代理对象
enhanced = enhancer.create(typesArray, valuesArray);
} catch (Exception e) {
throw new ExecutorException("Error creating lazy proxy. Cause: " + e, e);
}
// 设置回调对象
((Proxy) enhanced).setHandler(callback);
return enhanced;
}
/**
* 实现Javassist的MethodHandler接口, 相对于Cglib的MethodInterceptor
* 他们接口的方法名也是不一样的,Javassist的是invoke, 而cglib是intercept,叫法不同,实现功能是一样的
*/
private static class EnhancedResultObjectProxyImpl implements MethodHandler {
/**
* 目标类型
*/
private final Class<?> type;
/**
* 延迟加载Map集合
*/
private final ResultLoaderMap lazyLoader;
/**
* 是否配置延迟加载
*/
private final boolean aggressive;
/**
* 延迟加载触发的方法
*/
private final Set<String> lazyLoadTriggerMethods;
/**
* 对象工厂
*/
private final ObjectFactory objectFactory;
/**
* 构造函数类型数组
*/
private final List<Class<?>> constructorArgTypes;
/**
* 构造函数类型的值数组
*/
private final List<Object> constructorArgs;
/**
* 构造函数私有化了
* @param type
* @param lazyLoader
* @param configuration
* @param objectFactory
* @param constructorArgTypes
* @param constructorArgs
*/
private EnhancedResultObjectProxyImpl(Class<?> type, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
this.type = type;
this.lazyLoader = lazyLoader;
this.aggressive = configuration.isAggressiveLazyLoading();
this.lazyLoadTriggerMethods = configuration.getLazyLoadTriggerMethods();
this.objectFactory = objectFactory;
this.constructorArgTypes = constructorArgTypes;
this.constructorArgs = constructorArgs;
}
public static Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
// 获取目标类型
// 创建一个EnhancedResultObjectProxyImpl对象,回调对象
final Class<?> type = target.getClass();
EnhancedResultObjectProxyImpl callback = new EnhancedResultObjectProxyImpl(type, lazyLoader, configuration, objectFactory, constructorArgTypes, constructorArgs);
Object enhanced = crateProxy(type, callback, constructorArgTypes, constructorArgs);
PropertyCopier.copyBeanProperties(type, target, enhanced);
return enhanced;
}
/**
* 回调方法
* @param enhanced 代理对象
* @param method 方法
* @param methodProxy 代理方法
* @param args 入参
* @return
* @throws Throwable
*/
@Override
public Object invoke(Object enhanced, Method method, Method methodProxy, Object[] args) throws Throwable {
//获取方法名称
final String methodName = method.getName();
try {
synchronized (lazyLoader) {
if (WRITE_REPLACE_METHOD.equals(methodName)) {
//如果方法是writeReplace
Object original;
if (constructorArgTypes.isEmpty()) {
original = objectFactory.create(type);
} else {
original = objectFactory.create(type, constructorArgTypes, constructorArgs);
}
PropertyCopier.copyBeanProperties(type, enhanced, original);
if (lazyLoader.size() > 0) {
return new JavassistSerialStateHolder(original, lazyLoader.getProperties(), objectFactory, constructorArgTypes, constructorArgs);
} else {
return original;
}
} else {
//不是writeReplace方法
// 延迟加载长度大于0, 且不是finalize方法
// configuration配置延迟加载参数,延迟加载触发的方法包含这个方法
// 延迟加载所有数据
if (lazyLoader.size() > 0 && !FINALIZE_METHOD.equals(methodName)) {
if (aggressive || lazyLoadTriggerMethods.contains(methodName)) {
lazyLoader.loadAll();
} else if (PropertyNamer.isSetter(methodName)) {
final String property = PropertyNamer.methodToProperty(methodName);
lazyLoader.remove(property);
} else if (PropertyNamer.isGetter(methodName)) {
final String property = PropertyNamer.methodToProperty(methodName);
if (lazyLoader.hasLoader(property)) {
lazyLoader.load(property);
}
}
}
}
}
return methodProxy.invoke(enhanced, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
}
private static class EnhancedDeserializationProxyImpl extends AbstractEnhancedDeserializationProxy implements MethodHandler {
private EnhancedDeserializationProxyImpl(Class<?> type, Map<String, ResultLoaderMap.LoadPair> unloadedProperties, ObjectFactory objectFactory,
List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
super(type, unloadedProperties, objectFactory, constructorArgTypes, constructorArgs);
}
public static Object createProxy(Object target, Map<String, ResultLoaderMap.LoadPair> unloadedProperties, ObjectFactory objectFactory,
List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
final Class<?> type = target.getClass();
EnhancedDeserializationProxyImpl callback = new EnhancedDeserializationProxyImpl(type, unloadedProperties, objectFactory, constructorArgTypes, constructorArgs);
Object enhanced = crateProxy(type, callback, constructorArgTypes, constructorArgs);
PropertyCopier.copyBeanProperties(type, target, enhanced);
return enhanced;
}
@Override
public Object invoke(Object enhanced, Method method, Method methodProxy, Object[] args) throws Throwable {
final Object o = super.invoke(enhanced, method, args);
return o instanceof AbstractSerialStateHolder ? o : methodProxy.invoke(o, args);
}
@Override
protected AbstractSerialStateHolder newSerialStateHolder(Object userBean, Map<String, ResultLoaderMap.LoadPair> unloadedProperties, ObjectFactory objectFactory,
List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
return new JavassistSerialStateHolder(userBean, unloadedProperties, objectFactory, constructorArgTypes, constructorArgs);
}
}
private static class LogHolder {
private static final Log log = LogFactory.getLog(JavassistProxyFactory.class);
}
}