spring源碼系列10:AOP代理對象的執行

說完了AOP代理對象的建立,事務代理對象的建立,這文,講講AOP代理對象執行java

回顧:

  1. 靜態代理與JDK動態代理與CGLIB動態代理
  2. Spring中的InstantiationAwareBeanPostProcessor和BeanPostProcessor的區別
  3. spring源碼系列8:AOP源碼解析之代理的建立

靜態代理與JDK動態代理與CGLIB動態代理這一節咱們講過:spring

  • 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聯盟中的MethodInterceptorapp

下面逐個分析代理的執行。ide

AOP-JDK動態代理的執行

JDK動態代理執行:代理類方法-->InvocationHandler.invoke()-->目標方法 JdkDynamicAopProxy 是JDK動態代理的實現類。 JdkDynamicAopProxy自己是一個InvocationHandler,因此咱們執行代理的某個方法時,會通過JdkDynamicAopProxy.invoke方法而後去調用目標方法。post

@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種狀況:this

  • equals & hashCode 調用的是JdkDynamicAopProxy的equals & hashcode方法
  • DecoratingProxy 類& Advised接口的方法 都交由proy-config去執行,也就是this.advised
  • 其餘的方法,先獲取加強器鏈,執行加強器,再去執行目標對象方法。

重點看看第三種狀況:spa

  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方法,執行目標方法。

相關文章
相關標籤/搜索