• spring5.0源码解析 Aop 03 生成AopProxy对象


    AopProxy

    具体可以看上一篇文章

    AopProxy 的两个子类 CglibAopProxy 、 JdkDynamicAopProxy 分别采用不同的方式产生代理对象
    AopProxy 是 通过 AopProxyFactory 来生成的
    DefaultAopProxyFactory.createAopProxy 方法 根据 AdvisedSupport 生成AopProxy 这里决定了使用CGLIB还是Jdk的的方式

    JDK生成AopProxy代理对象

    在生成 Proxy之前,首先需要从advised对象中获取代理对象的代理接口配置,然后调用 Proxy的newProxyInstance 方法,最终得到 Proxy 代理对象,在生成代理对象时,需要指定三个参数,一个时类加载器,一个是代理接口,一个是Proxy回调方法所在的对象,这个对象需要实现InvocationHandler接口,这个接口顶一个 invoke方法,提供代理对象的回调入口。对于 JdkDynamicAopProxy 他本身实现了 InvocationHandler接口的 invoke 方法,这个回调接口完成了AOP编织实现的封装。

    构造方法主要是 this.advised = config; 保存配置信息

    // 为给定的AOP配置构造一个新的JdkDynamicAopProxy。
    	public JdkDynamicAopProxy(AdvisedSupport config) throws AopConfigException {
    		Assert.notNull(config, "AdvisedSupport must not be null");
    		if (config.getAdvisorCount() == 0 && config.getTargetSource() == AdvisedSupport.EMPTY_TARGET_SOURCE) {
    			throw new AopConfigException("No advisors and no TargetSource specified");
    		}
    		// config 里包含了 advice 和 pointCut
    		this.advised = config;
    		this.proxiedInterfaces = AopProxyUtils.completeProxiedInterfaces(this.advised, true);
    		// 判断是否重新定义了 hashCode 和 equals 方法
    		findDefinedEqualsAndHashCodeMethods(this.proxiedInterfaces);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    获取一个代理对象

    	@Override
    	public Object getProxy(@Nullable ClassLoader classLoader) {
    		if (logger.isTraceEnabled()) {
    			logger.trace("Creating JDK dynamic proxy: " + this.advised.getTargetSource());
    		}
    		//使用 jdk 的Proxy 生成代理对象 //  this 实现了 InvocationHandler接口
    		return Proxy.newProxyInstance(classLoader, this.proxiedInterfaces, this);
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    重写了 InvocationHandler的invoke

    实现了invoke接口完成了 代理对象的目标方法的执行流程 其中真正的拦截器链拦截的现实 通过
    MethodInvocation 来完成

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    		Object oldProxy = null;
    		boolean setProxyContext = false;
    		// 保存被代理的目标对象
    		TargetSource targetSource = this.advised.targetSource;
    		Object target = null;
    
    		try {
    			// 代理目标没有重写 equals
    			if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
    				// The target does not implement the equals(Object) method itself.
    				return equals(args[0]);
    			}
    			// 代理目标没有重写 hashCode
    			else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
    				// The target does not implement the hashCode() method itself.
    				return hashCode();
    			}
    			// 只有getDecoratedClass()声明->分派到代理配置。
    			else if (method.getDeclaringClass() == DecoratingProxy.class) {
    				// There is only getDecoratedClass() declared -> dispatch to proxy config.
    				return AopProxyUtils.ultimateTargetClass(this.advised);
    			}
    			//如果目标对象是Advice类型,则直接使用反射进行调用
    			//opaque-->标记是否需要阻止通过该配置创建的代理对象转换为Advised类型,默认值为false,表示代理对象可以被转换为Advised类型
    			else if (!this.advised.opaque && method.getDeclaringClass().isInterface() &&
    					method.getDeclaringClass().isAssignableFrom(Advised.class)) {
    				// Service invocations on ProxyConfig with the proxy config...
    				return AopUtils.invokeJoinpointUsingReflection(this.advised, method, args);
    			}
    
    			Object retVal;
    			// 判断是否需要用 AopContext 或者 threadLock 暴漏出去
    			if (this.advised.exposeProxy) {
    				// Make invocation available if necessary.
    				oldProxy = AopContext.setCurrentProxy(proxy);
    				setProxyContext = true;
    			}
    
    			// Get as late as possible to minimize the time we "own" the target,
    			// in case it comes from a pool.
    			target = targetSource.getTarget(); // 获取目标对象
    			Class<?> targetClass = (target != null ? target.getClass() : null);  // 获取目标对象的类类型
    
    			//获取此方法的拦截链。
    			List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
    
    			// Check whether we have any advice. If we don't, we can fallback on direct
    			// reflective invocation of the target, and avoid creating a MethodInvocation.
    			// 如果拦截链为空,直接返回调到该方法
    			if (chain.isEmpty()) {
    				// We can skip creating a MethodInvocation: just invoke the target directly
    				// Note that the final invoker must be an InvokerInterceptor so we know it does
    				// nothing but a reflective operation on the target, and no hot swapping or fancy proxying.
    				//我们可以跳过创建MethodInvocation:直接调用目标
    				//请注意,最后一个调用程序必须是InvokerInterceptor,因此我们知道它是这样的
    				//只有对目标的反射操作,没有热交换或奇特的代理。
    				Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
    				retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
    			}
    			else {
    				// 否则创建 MethodInvocation 执行拦截调用
    				MethodInvocation invocation =
    						new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
    				// 通过拦截器链进入连接点。返回连接点的值
    				retVal = invocation.proceed();
    			}
    
    			// Massage return value if necessary.
    			// 获取目标方法返回值类型
    			Class<?> returnType = method.getReturnType();
    			if (retVal != null && retVal == target &&
    					returnType != Object.class && returnType.isInstance(proxy) &&
    					!RawTargetAccess.class.isAssignableFrom(method.getDeclaringClass())) {
    				// Special case: it returned "this" and the return type of the method
    				// is type-compatible. Note that we can't help if the target sets
    				// a reference to itself in another returned object.
    				retVal = proxy;
    			}
    			else if (retVal == null && returnType != Void.TYPE && returnType.isPrimitive()) {
    				throw new AopInvocationException(
    						"Null return value from advice does not match primitive return type for: " + method);
    			}
    			return retVal;
    		}
    		finally {
    			if (target != null && !targetSource.isStatic()) {
    				// Must have come from TargetSource.
    				// 释放从中获得的给定目标对象
    				targetSource.releaseTarget(target);
    			}
    			if (setProxyContext) {
    				// Restore old proxy.
    				AopContext.setCurrentProxy(oldProxy);
    			}
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97

    MethodInvocation 的 proceed 方法

    递归调用 proceed 保证 advice 都被执行 采用 currentInterceptorIndex 计数 保证 每个拦截器只执行一次 并且 invokeJoinpoint也只执行一次 执行 invokeJoinpoint 过程中能够 其他 advice 可能没有执行完全

    	public Object proceed() throws Throwable {
    		// We start with an index of -1 and increment early.
    		// 我们从指数-1开始,并提前递增。 递归调用 所有拦截器链中的 Matcher 的 advice
    		if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
    			// 运行目标对象的方法  也就是反射调用的指定目标
    			return invokeJoinpoint();
    		}
    
    		Object interceptorOrInterceptionAdvice =
    				this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
    		// 判断advice 是不是 InterceptorAndDynamicMethodMatcher 的子类 则 advice 有 match的English
    		if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
    			// Evaluate dynamic method matcher here: static part will already have
    			// been evaluated and found to match.
    			InterceptorAndDynamicMethodMatcher dm =
    					(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
    			Class<?> targetClass = (this.targetClass != null ? this.targetClass : this.method.getDeclaringClass());
    			if (dm.methodMatcher.matches(this.method, targetClass, this.arguments)) {
    				return dm.interceptor.invoke(this);
    			}
    			else {
    				// Dynamic matching failed.
    				// Skip this interceptor and invoke the next in the chain.
    				return proceed();
    			}
    		}
    		else {
    			// It's an interceptor, so we just invoke it: The pointcut will have
    			// been evaluated statically before this object was constructed.
    			// 它是一个拦截器,直接调用 他的 invoke方法 可能是Interceptor 的 invoke 也有可能是 advice 的 invoke
    			return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
    		}
    	}
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    CGLIB生成AopProxy代理对象

    CglibAopProxy 通过 intercept进行拦截
    也是通过 CglibMethodInvocation 执行 目标方法与拦截器

  • 相关阅读:
    C语言C位出道心法(四):文件操作
    k8s-----26、细粒度权限管理 RBAC
    嵌入式 程序调试之gdb和gdbserver的交叉编译及使用
    计算机毕业设计SSM“花点时间”在线图书超市【附源码数据库】
    C++入门第七篇--STL模板--vector模拟实现
    芯片检测哪家强?
    IO模型复习
    lambda表达式,函数式接口和方法引用
    第十五届蓝桥杯(Web 应用开发)模拟赛 3 期-大学组(被题目描述坑惨了)
    JavaScript如何实现钟表效果,时分秒针指向当前时间,并显示当前年月日,及2024春节倒计时,源码奉上
  • 原文地址:https://blog.csdn.net/qq_44808472/article/details/126272972