public class ProxyFactory extends ProxyCreatorSupport {
// 创建代理对象
public Object getProxy() {
// 创建代理工厂
this.aopProxyFactory = new DefaultAopProxyFactory();
// 获取代理对象
return this.aopProxyFactory.getProxy() {
// 如果需要优化性能,或者是设置了CGLIB代理,或者该类没有实现有意义的接口,就是用户定义的接口
if (config.isOptimize() || config.isProxyTargetClass() || hasNoUserSuppliedProxyInterfaces(config)) {
// 获取到目标类
Class<?> targetClass = config.getTargetClass();
// 如果目标类是一个接口,或者目标类是一个JDK代理对象,使用JDK代理
// 这里是处理接口的default默认方法的操作
if (targetClass.isInterface() || Proxy.isProxyClass(targetClass)) {
return new JdkDynamicAopProxy(config);
}
// 否则使用CGLIB代理
return new ObjenesisCglibAopProxy(config) {
// 获取目标类
Class<?> rootClass = this.advised.getTargetClass();
// 目标类就是代理的父类
Class<?> proxySuperClass = rootClass;
// 如果类已经是CGLIB代理的类
if(rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)){
// 还要获取到具体的目标原始类
proxySuperClass = rootClass.getSuperclass();
// 获取代理类实现的接口
Class<?>[] additionalInterfaces = rootClass.getInterfaces();
// 保存这些接口
for (Class<?> additionalInterface : additionalInterfaces) {
this.advised.addInterface(additionalInterface);
}
}
// 配置CGLIB增强器,创建代理对象
Enhancer enhancer = createEnhancer();
enhancer.setSuperclass(proxySuperClass);
enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
enhancer.setStrategy(new
ClassLoaderAwareGeneratorStrategy(classLoader));
Callback[] callbacks = getCallbacks(rootClass){
// 这个拦截器是拦截器CGLIB代理对象的intercept方法
Callback aopInterceptor = new DynamicAdvisedInterceptor(this.advised);
// ...,还有其他的拦截器
}
enhancer.setCallbackFilter(new
ProxyCallbackFilter(this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap,this.fixedInterceptorOffset));
enhancer.setCallbackTypes(types);
// 创建实例
return createProxyClassAndInstance(enhancer, callbacks) {
enhancer.setInterceptDuringConstruction(false);
enhancer.setCallbacks(callbacks);
// 使用增强器创建代理对象
return (this.constructorArgs != null && this.constructorArgTypes != null ?
enhancer.create(this.constructorArgTypes, this.constructorArgs) :
enhancer.create());
}
}
} else {
// 其他条件,表示实现了接口,使用JDK动态代理
return new JdkDynamicAopProxy(config) {
// 计算需要实现的接口
Class<?>[] proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
findDefinedEqualsAndHashCodeMethods(proxiedInterfaces);
// 使用JDK代理
return Proxy.newProxyInstance(classLoader,proxiedInterfaces,this);
}
}
}
}
}
Spring使用ProxyFactory创建代理对象源码解析
最新推荐文章于 2025-05-29 11:50:19 发布
本文详细描述了如何在Spring框架中创建代理对象,涉及CGLIB和JDK动态代理的选择过程,以及在不同条件下如何配置Enhancer和Interceptor以实现AOP代理功能。
843

被折叠的 条评论
为什么被折叠?



