2023-09-16
原文作者:王伟王胖胖 原文地址: https://blog.csdn.net/wangwei19871103/article/details/105226996

JdkDynamicAopProxy的getProxy

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

202309162317558851.png

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;
    	}

202309162317563712.png

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;
    	}

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

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

好了,今天就到这里了,希望对学习理解有帮助,大神看见勿喷,仅为自己的学习理解,能力有限,请多包涵。

阅读全文