Cglib 代理工厂类,为了实现延迟加载属性
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import net.sf.cglib.proxy.Callback;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;
import org.apache.ibatis.executor.loader.AbstractEnhancedDeserializationProxy;
import org.apache.ibatis.executor.loader.AbstractSerialStateHolder;
import org.apache.ibatis.executor.loader.ProxyFactory;
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;
/**
* cglib代理工厂类,实现延迟加载属性
* @author Clinton Begin
*/
public class CglibProxyFactory implements ProxyFactory {
/**
* finalize方法
*/
private static final String FINALIZE_METHOD = "finalize";
/**
* writeReplace方法
*/
private static final String WRITE_REPLACE_METHOD = "writeReplace";
/**
* 加载Enhancer,这个是Cglib的入口
*/
public CglibProxyFactory() {
try {
Resources.classForName("net.sf.cglib.proxy.Enhancer");
} catch (Throwable e) {
throw new IllegalStateException("Cannot enable lazy loading because CGLIB is not available. Add CGLIB to your classpath.", e);
}
}
/**
* 创建代理对象
* @param target 目标对象
* @param lazyLoader 延迟加载器
* @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);
}
/**
* 创建一个反序列化代理
* @param target 目标
* @param unloadedProperties
* @param objectFactory 对象工厂
* @param constructorArgTypes 构造函数类型数组
* @param constructorArgs 构造函数值
* @return
*/
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
}
/**
* 返回代理对象, 这个代理对象在调用任何方法都会调用本类的intercept方法
* Enhancer 认为这个就是自定义类的工厂,比如这个类需要实现什么接口
* @param type 目标类型
* @param callback 结果对象代理实现类,当中有invoke回调方法
* @param constructorArgTypes 构造函数类型数组
* @param constructorArgs 构造函数对应字段的值数组
* @return
*/
static Object crateProxy(Class<?> type, Callback callback, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
// enhancer 配置调节代理对象的一些参数
// 设置回调方法
// 设置超类
//判断当传入目标类型是否有writeReplace方法,没有则配置一个有writeReplace方法的接口(序列化写出)
Enhancer enhancer = new Enhancer();
enhancer.setCallback(callback);
enhancer.setSuperclass(type);
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增加一个WriteReplaceInterface接口
enhancer.setInterfaces(new Class[]{WriteReplaceInterface.class});
} catch (SecurityException e) {
// nothing to do here
}
//根据构造函数创建一个对象
//无参构造
//有参构造
Object enhanced;
if (constructorArgTypes.isEmpty()) {
enhanced = enhancer.create();
} else {
Class<?>[] typesArray = constructorArgTypes.toArray(new Class[constructorArgTypes.size()]);
Object[] valuesArray = constructorArgs.toArray(new Object[constructorArgs.size()]);
enhanced = enhancer.create(typesArray, valuesArray);
}
return enhanced;
}
/**
* 结果对象代理实现类,
* 它实现方法拦截器的intercept方法
*/
private static class EnhancedResultObjectProxyImpl implements MethodInterceptor {
private final Class<?> type;
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 目标class类型
* @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;
}
/**
* 创建代理对象, 将源对象值赋值给代理对象
* @param target 目标对象
* @param lazyLoader 延迟加载器
* @param configuration 配置对象
* @param objectFactory 对象工厂
* @param constructorArgTypes 构造函数类型数组
* @param constructorArgs 构造函数值数组
* @return
*/
public static Object createProxy(Object target, ResultLoaderMap lazyLoader, Configuration configuration, ObjectFactory objectFactory, List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
//获取目标的类型
//创建一个结果对象代理实现类(它实现cglib的MethodInterface接口,完成回调作用invoke方法)
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 args 方法参数
* @param methodProxy 代理方法
* @return
* @throws Throwable
*/
@Override
public Object intercept(Object enhanced, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
//获取方法名
final String methodName = method.getName();
try {
// 同步获取延迟加载对象
// 如果是执行writeReplace方法(序列化写出)
// 实例化一个目标对象的实例
synchronized (lazyLoader) {
if (WRITE_REPLACE_METHOD.equals(methodName)) {
Object original;
if (constructorArgTypes.isEmpty()) {
original = objectFactory.create(type);
} else {
original = objectFactory.create(type, constructorArgTypes, constructorArgs);
}
// 将enhanced中的属性复制到orignal对象中
// 如果延迟加载数量>0,
PropertyCopier.copyBeanProperties(type, enhanced, original);
if (lazyLoader.size() > 0) {
return new CglibSerialStateHolder(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();
// setter方法,直接移除
} else if (PropertyNamer.isSetter(methodName)) {
final String property = PropertyNamer.methodToProperty(methodName);
lazyLoader.remove(property);
// getter方法, 加载该属性
} else if (PropertyNamer.isGetter(methodName)) {
final String property = PropertyNamer.methodToProperty(methodName);
if (lazyLoader.hasLoader(property)) {
lazyLoader.load(property);
}
}
}
}
}
return methodProxy.invokeSuper(enhanced, args);
} catch (Throwable t) {
throw ExceptionUtil.unwrapThrowable(t);
}
}
}
/**
* 他继承抽象反序列化代理和实现了方法拦截
*/
private static class EnhancedDeserializationProxyImpl extends AbstractEnhancedDeserializationProxy implements MethodInterceptor {
private EnhancedDeserializationProxyImpl(Class<?> type, Map<String, ResultLoaderMap.LoadPair> unloadedProperties, ObjectFactory objectFactory,
List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
super(type, unloadedProperties, objectFactory, constructorArgTypes, constructorArgs);
}
/**
* 创建代理对象
* @param target
* @param unloadedProperties
* @param objectFactory
* @param constructorArgTypes
* @param constructorArgs
* @return
*/
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 intercept(Object enhanced, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
final Object o = super.invoke(enhanced, method, args);
return o instanceof AbstractSerialStateHolder ? o : methodProxy.invokeSuper(o, args);
}
@Override
protected AbstractSerialStateHolder newSerialStateHolder(Object userBean, Map<String, ResultLoaderMap.LoadPair> unloadedProperties, ObjectFactory objectFactory,
List<Class<?>> constructorArgTypes, List<Object> constructorArgs) {
return new CglibSerialStateHolder(userBean, unloadedProperties, objectFactory, constructorArgTypes, constructorArgs);
}
}
private static class LogHolder {
private static final Log log = LogFactory.getLog(CglibProxyFactory.class);
}
}