Spring 5.x 源码之旅-48AOP代理细节三JdkDynamicAopProxy和CglibAopProxy

作者简介:大家好,我是smart哥,前中兴通讯、美团架构师,现某互联网公司CTO

联系qq:184480602,加我进群,大家一起学习,一起进步,一起对抗互联网寒冬

学习必须往深处挖,挖的越深,基础越扎实!

阶段1、深入多线程

阶段2、深入多线程设计模式

阶段3、深入juc源码解析


阶段4、深入jdk其余源码解析


阶段5、深入jvm源码解析

码哥源码部分

码哥讲源码-原理源码篇【2024年最新大厂关于线程池使用的场景题】

码哥讲源码【炸雷啦!炸雷啦!黄光头他终于跑路啦!】

码哥讲源码-【jvm课程前置知识及c/c++调试环境搭建】

​​​​​​码哥讲源码-原理源码篇【揭秘join方法的唤醒本质上决定于jvm的底层析构函数】

码哥源码-原理源码篇【Doug Lea为什么要将成员变量赋值给局部变量后再操作?】

码哥讲源码【你水不是你的错,但是你胡说八道就是你不对了!】

码哥讲源码【谁再说Spring不支持多线程事务,你给我抽他!】

终结B站没人能讲清楚红黑树的历史,不服等你来踢馆!

打脸系列【020-3小时讲解MESI协议和volatile之间的关系,那些将x86下的验证结果当作最终结果的水货们请闭嘴】

JdkDynamicAopProxy的getProxy

主要是JdkDynamicAopProxy在代理前还有一些事情要说下:

AopProxyUtils的completeProxiedInterfaces

这里说白了就是增加一些其他的接口SpringProxyDecoratingProxyAdvised

    static Class<?>[] completeProxiedInterfaces(AdvisedSupport advised, boolean decoratingProxy) {
    		Class<?>[] specifiedInterfaces = advised.getProxiedInterfaces();
    		if (specifiedInterfaces.length == 0) {
    			// No user-specified interfaces: check whether target class is an interface.
    			Class<?> targetClass = advised.getTargetClass();
    			if (targetClass != null) {
    				if (targetClass.isInterface()) {
    					advised.setInterfaces(targetClass);
    				}
    				else if (Proxy.isProxyClass(targetClass)) {
    					advised.setInterfaces(targetClass.getInterfaces());
    				}
    				specifiedInterfaces = advised.getProxiedInterfaces();
    			}
    		}
    		boolean addSpringProxy = !advised.isInterfaceProxied(SpringProxy.class);
    		boolean addAdvised = !advised.isOpaque() && !advised.isInterfaceProxied(Advised.class);
    		boolean addDecoratingProxy = (decoratingProxy && !advised.isInterfaceProxied(DecoratingProxy.class));
    		int nonUserIfcCount = 0;
    		if (addSpringProxy) {//需要添加SpringProxy接口
    			nonUserIfcCount++;
    		}
    		if (addAdvised) {//需要添加通知
    			nonUserIfcCount++;
    		}
    		if (addDecoratingProxy) {//需要添加DecoratingProxy接口
    			nonUserIfcCount++;
    		}
    		Class<?>[] proxiedInterfaces = new Class<?>[specifiedInterfaces.length + nonUserIfcCount];
    		System.arraycopy(specifiedInterfaces, 0, proxiedInterfaces, 0, specifiedInterfaces.length);
    		int index = specifiedInterfaces.length;
    		if (addSpringProxy) {
    			proxiedInterfaces[index] = SpringProxy.class;
    			index++;
    		}
    		if (addAdvised) {
    			proxiedInterfaces[index] = Advised.class;
    			index++;
    		}
    		if (addDecoratingProxy) {
    			proxiedInterfaces[index] = DecoratingProxy.class;
    		}
    		return proxiedInterfaces;
    	}

CglibAopProxy的getProxy

就是CGLIB的基本用法,创建增强器,拦截器,设置父类等

    @Override
    	public Object getProxy(@Nullable ClassLoader classLoader) {
    		if (logger.isTraceEnabled()) {
    			logger.trace("Creating CGLIB proxy: " + this.advised.getTargetSource());
    		}
    
    		try {
    			Class<?> rootClass = this.advised.getTargetClass();
    			Assert.state(rootClass != null, "Target class must be available for creating a CGLIB proxy");
    
    			Class<?> proxySuperClass = rootClass;
    			if (rootClass.getName().contains(ClassUtils.CGLIB_CLASS_SEPARATOR)) {//类名是否包含CGLIB分隔符
    				proxySuperClass = rootClass.getSuperclass();
    				Class<?>[] additionalInterfaces = rootClass.getInterfaces();//获得原始父类的接口
    				for (Class<?> additionalInterface : additionalInterfaces) {
    					this.advised.addInterface(additionalInterface);
    				}
    			}
    			//验证修饰符和方法修饰符
    			// Validate the class, writing log messages as necessary.
    			validateClassIfNecessary(proxySuperClass, classLoader);
    
    			// Configure CGLIB Enhancer...
    			Enhancer enhancer = createEnhancer();//增强器
    			if (classLoader != null) {
    				enhancer.setClassLoader(classLoader);
    				if (classLoader instanceof SmartClassLoader &&
    						((SmartClassLoader) classLoader).isClassReloadable(proxySuperClass)) {
    					enhancer.setUseCache(false);
    				}
    			}
    			enhancer.setSuperclass(proxySuperClass);//父类
    			enhancer.setInterfaces(AopProxyUtils.completeProxiedInterfaces(this.advised));
    			enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
    			enhancer.setStrategy(new ClassLoaderAwareGeneratorStrategy(classLoader));
    
    			Callback[] callbacks = getCallbacks(rootClass);
    			Class<?>[] types = new Class<?>[callbacks.length];
    			for (int x = 0; x < types.length; x++) {
    				types[x] = callbacks[x].getClass();
    			}
    			// fixedInterceptorMap only populated at this point, after getCallbacks call above
    			enhancer.setCallbackFilter(new ProxyCallbackFilter(
    					this.advised.getConfigurationOnlyCopy(), this.fixedInterceptorMap, this.fixedInterceptorOffset));
    			enhancer.setCallbackTypes(types);
    
    			// Generate the proxy class and create a proxy instance.
    			return createProxyClassAndInstance(enhancer, callbacks);
    		}
    		catch (CodeGenerationException | IllegalArgumentException ex) {
    			throw new AopConfigException("Could not generate CGLIB subclass of " + this.advised.getTargetClass() +
    					": Common causes of this problem include using a final class or a non-visible class",
    					ex);
    		}
    		catch (Throwable ex) {
    			// TargetSource.getTarget() failed
    			throw new AopConfigException("Unexpected AOP exception", ex);
    		}
    	}

ObjenesisCglibAopProxy的createProxyClassAndInstance

生成代理类,然后用objenesis生成实例。

    @Override
    	protected Object createProxyClassAndInstance(Enhancer enhancer, Callback[] callbacks) {
    		Class<?> proxyClass = enhancer.createClass();
    		Object proxyInstance = null;
    
    		if (objenesis.isWorthTrying()) {
    			try {
    				proxyInstance = objenesis.newInstance(proxyClass, enhancer.getUseCache());
    			}
    			catch (Throwable ex) {
    				logger.debug("Unable to instantiate proxy using Objenesis, " +
    						"falling back to regular proxy construction", ex);
    			}
    		}
    
    		if (proxyInstance == null) {
    			// Regular instantiation via default constructor...
    			try {
    				Constructor<?> ctor = (this.constructorArgs != null ?
    						proxyClass.getDeclaredConstructor(this.constructorArgTypes) :
    						proxyClass.getDeclaredConstructor());
    				ReflectionUtils.makeAccessible(ctor);
    				proxyInstance = (this.constructorArgs != null ?
    						ctor.newInstance(this.constructorArgs) : ctor.newInstance());
    			}
    			catch (Throwable ex) {
    				throw new AopConfigException("Unable to instantiate proxy using Objenesis, " +
    						"and regular proxy instantiation via default constructor fails as well", ex);
    			}
    		}
    
    		((Factory) proxyInstance).setCallbacks(callbacks);
    		return proxyInstance;
    	}

最后还会设置一些回调器:


了解到这里就差不多知道是怎么生成AOP代理了,接下去就看看哪些方法是怎么执行的吧。

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值