spring源码系列10:AOP代理对象的执行

说完了AOP代理对象的创建,事务代理对象的创建,这文,讲讲AOP代理对象执行

回顾:

  1. 静态代理与JDK动态代理与CGLIB动态代理
  2. Spring中的InstantiationAwareBeanPostProcessor和BeanPostProcessor的区别
  3. spring源码系列8:AOP源码解析之代理的创建

静态代理与JDK动态代理与CGLIB动态代理这一节我们讲过:

  • JDK动态代理会在内存中生成一个类名为$Proxy0形式的代理类,
  • 调用$Proxy0方法,内部调用父类Proxy.InvocationHandler.invoke方法
  • JDK动态代理执行链:代理类方法–>InvocationHandler.invoke()–>目标方法

  • CGLB动态代理会在内存生成一个类名为UserNoInterface$$EnhancerByCGLIB$$b3361405形式的代理类
  • 调用xxx$$EnhancerByCGLIB$$b3361405代理类方法,内部调用MethodInterceptor.intercept()
  • CGLB动态代理执行链: 代理类方法–>MethodInterceptor.intercept()–>目标方法

SpringAop是通过JDK动态代理或者CGLB动态代理实现的,他也会有如上特征。

  • AOP的JDK动态代实现是通过把Advised封装到InvocationHandler中实现的
  • AOP的CGLB动态实现是通过把Advised封装到MethodInterceptor中实现的。

注意: 此处的MethodInterceptor是CGLB中的。 区别于AOP联盟中的MethodInterceptor

下面逐个分析代理的执行。

AOP-JDK动态代理的执行

JDK动态代理执行:代理类方法–>InvocationHandler.invoke()–>目标方法
JdkDynamicAopProxy 是JDK动态代理的实现类。
JdkDynamicAopProxy本身是一个InvocationHandler,所以我们执行代理的某个方法时,会经过JdkDynamicAopProxy.invoke方法然后去调用目标方法。

@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		MethodInvocation invocation;
		Object oldProxy = null;
		boolean setProxyContext = false;

		TargetSource targetSource = this.advised.targetSource;
		Class<?> targetClass = null;
		Object target = null;

		try {
			if (!this.equalsDefined && AopUtils.isEqualsMethod(method)) {
				// The target does not implement the equals(Object) method itself.
				return equals(args[0]);
			}
			else if (!this.hashCodeDefined && AopUtils.isHashCodeMethod(method)) {
				// The target does not implement the hashCode() method itself.
				return hashCode();
			}
			else if (method.getDeclaringClass() == DecoratingProxy.class) {
				// There is only getDecoratedClass() declared -> dispatch to proxy config.
				return AopProxyUtils.ultimateTargetClass(this.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上下文中,
			//这样在本线程的其他地方也可以获取到代理对象了。
			if (this.advised.exposeProxy) {
				// Make invocation available if necessary.
				oldProxy = AopContext.setCurrentProxy(proxy);
				setProxyContext = true;
			}

			// May be null. Get as late as possible to minimize the time we "own" the target,
			// in case it comes from a pool.
			target = targetSource.getTarget();
			if (target != null) {
				targetClass = target.getClass();
			}

			// Get the interception chain for this method.
			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.
				Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
				retVal = AopUtils.invokeJoinpointUsingReflection(target, method, argsToUse);
			}
			else {
				// We need to create a method invocation...
				invocation = new ReflectiveMethodInvocation(proxy, target, method, args, targetClass, chain);
				// Proceed to the joinpoint through the interceptor 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);
			}
		}
	}

这里分为3种情况:

  • equals & hashCode 调用的是JdkDynamicAopProxy的equals & hashcode方法
  • DecoratingProxy 类& Advised接口的方法 都交由proy-config去执行,也就是this.advised
  • 其他的方法,先获取增强器链,执行增强器,再去执行目标对象方法。

重点看看第三种情况:

  1. 通过advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass)获取增强器链chain
public List<Object> getInterceptorsAndDynamicInterceptionAdvice(Method method, Class<?> targetClass) {
		MethodCacheKey cacheKey = new MethodCacheKey(method);
		List<Object> cached = this.methodCache.get(cacheKey);
		if (cached == null) {
			cached = this.advisorChainFactory.getInterceptorsAndDynamicInterceptionAdvice(
					this, method, targetClass);
			this.methodCache.put(cacheKey, cached);
		}
		return cached;
	}

这里也用了缓存设计,如果缓存中为null。则使用DefaultAdvisorChainFactory工厂类获取增强器链chain。
获取的原理: 遍历所有适用当前类的Advisor,通过AdvisorAdapterRegistry适配器,将Advisor的每一个Advice,适配成MethodInterceptor。

  1. 如果获取增强器链为空。 则使用反射执行目标对象方法。
  2. 如果增强器链不为空,则创建一个方法执行器MethodInvocation(此处创建的是ReflectiveMethodInvocation)封装增强链+目标方法。然后调用MethodInvocation.proceed()递归执行所有增强器Adivce,执行Advice.invoke()方法进行拦截处理,在链的尾部通过反射执行目标方法。

接下来,就是处理返回值。

至此:AOP-JDK动态代理的执行就完成。

调用方法–>动态代理.方法–>InvocationHandler.invoke–>MethodInvocation.proceed执行增强器链–>Adivce.invoke方法–>目标方法

AOP-CGLB动态代理的执行

CGLB动态代理执行:代理类方法–>MethodInterceptor.intercept()–>目标方法
CglibAopProxy是CGLB动态代理的实现类。
CglibAopProxy会创建一个DynamicAdvisedInterceptor来拦截目标方法的执行。DynamicAdvisedInterceptor实现了MethodInterceptor。当我们执行代理的某个方法时,会经过DynamicAdvisedInterceptor.intercept()方法然后去调用目标方法。

我们看看这个方法

@Override
		public Object intercept(Object proxy, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
			Object oldProxy = null;
			boolean setProxyContext = false;
			Class<?> targetClass = null;
			Object target = null;
			try {
				if (this.advised.exposeProxy) {
					// Make invocation available if necessary.
					oldProxy = AopContext.setCurrentProxy(proxy);
					setProxyContext = true;
				}
				// May be null. Get as late as possible to minimize the time we
				// "own" the target, in case it comes from a pool...
				target = getTarget();
				if (target != null) {
					targetClass = target.getClass();
				}
				List<Object> chain = this.advised.getInterceptorsAndDynamicInterceptionAdvice(method, targetClass);
				Object retVal;
				// Check whether we only have one InvokerInterceptor: that is,
				// no real advice, but just reflective invocation of the target.
				if (chain.isEmpty() && Modifier.isPublic(method.getModifiers())) {
					// 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.
					Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
					retVal = methodProxy.invoke(target, argsToUse);
				}
				else {
					// We need to create a method invocation...
					retVal = new CglibMethodInvocation(proxy, target, method, args, targetClass, chain, methodProxy).proceed();
				}
				retVal = processReturnType(proxy, target, method, retVal);
				return retVal;
			}
			finally {
				if (target != null) {
					releaseTarget(target);
				}
				if (setProxyContext) {
					// Restore old proxy.
					AopContext.setCurrentProxy(oldProxy);
				}
			}
		}

可以看出跟AOP-CGLB动态代理与AOP-JDK动态 有很多相似之处。

  • 首先判断是否暴露代理。如果暴露,就把代理放到AopContext中,以便在其他地方也可以拿到
  • 和JDK Proxy中是一样的,通过DefaultAdvisorChainFactory工厂类获取增强器链chain
  • 增强器链isEmpty(),同时是public方法的话,使用反射执行目标方法(不拦截)
  • 增强链不为空,则创建一个方法执行器MethodInvocation(此处创建的是CglibMethodInvocation)封装增强链+目标方法,执行MethodInvocation.proceed() 。 因为CglibMethodInvocation是ReflectiveMethodInvocation的子类,所以后面就跟JDKproxy的执行一样了。
  • 最后就是处理返回值。

至此:AOP-CGLB动态代理的执行就完成。

调用方法–>动态代理类.方法–>MethodInterceptor.intercept方法–>MethodInvocation.proceed执行增强器链–>Adivce.invoke方法–>目标方法

总结

  • springaop是基于jdk动态代理与cglb动态代理。

  • springAop把拦截器封装成Advice,组成Advice链。封装到MethodInterceptor或者InvocationHandler中。当调用方法时,都会先调用代理类方法,经过增强器链的调用每个Adivce.invoke方法,执行目标方法。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值