Spring AOP 执行流程原理

AOP 执行流程原理

// 执行目标方法时 会先执行
org.springframework.aop.framework.CglibAopProxy
.DynamicAdvisedIntercepto
.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.
		//检查我们是否只有一个InvokerInterceptor:也就是说,没有真正的建议,只是对目标的反射调用。
		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.
		//	我们可以跳过创建方法调用:直接调用目标。注意,最终的调用程序必须是InvokerInterceptor,
		//所以我们知道它只对目标执行反射操作,没有热交换或花哨的代理。
			Object[] argsToUse = AopProxyUtils.adaptArgumentsIfNecessary(method, args);
			retVal = methodProxy.invoke(target, argsToUse);
		}
		else {
			// We need to create a method invocation...
			// 我们需要创建一个方法调用…
			<!--CglibMethodInvocation 的.proceed() 方法才是最终实行我们设置的方法通知的增强器接口-->
			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);
		}
	}
}


CglibMethodInvocation.proceed() 方法的执行过程
org.springframework.aop.framework.ReflectiveMethodInvocation
.proceed() throws Throwable {
	//	We start with an index of -1 and increment early.
	<!-- currentInterceptorIndex 初始为 -1 只在两种情况下执行该IF代码块中的代码 
	(1). 方法拦截器链为空的情况下
	(2). 方法拦截器链执行到最后的情况下爱执行 -->
	if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
	    // 利用反射去执行目标方法
		return invokeJoinpoint();
	}

    // 从方法拦截器链中获取一个方法拦截器 从下表 0 递增
	Object interceptorOrInterceptionAdvice =
			this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
	if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
		// Evaluate dynamic method matcher here: static part will already have
		// been evaluated and found to match.
		//评估动态方法匹配器这里:静态部分将已经评估并找到匹配。
		InterceptorAndDynamicMethodMatcher dm =
				(InterceptorAndDynamicMethodMatcher) interceptorOrInterceptionAdvice;
		if (dm.methodMatcher.matches(this.method, this.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.
		// 它是一个拦截器,所以我们只是调用它:切入点将在构造这个对象之前被静态地计算。
		<!--当前 MethodInterceptor 调用invoke(this) 方法的执行
		在下方进行拆解 -->
		return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
	}
	
第一次调用 invoke(this) 方法 拦截器链中第一个拦截器调用
org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke (MethodInvocation mi) throws Throwable {
	MethodInvocation oldInvocation = invocation.get();
	//设置当前线程的变量
	invocation.set(mi);
	try {
	    //再次执行 proceed()方法org.springframework.aop.framework.ReflectiveMethodInvocation.proceed()
	    
		return mi.proceed();
	}
	finally {
		invocation.set(oldInvocation);
	}
}
第二次调用 invoke(this) 方法 拦截器链中第二个拦截器调用
//  实为 @AfterThrowing 注解的方法拦截器
org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke (MethodInvocation mi) throws Throwable {
		try {
		//  再次调用 proceed 方法
			return mi.proceed();
		}
		catch (Throwable ex) {
			if (shouldInvokeOnThrowing(ex)) {
				invokeAdviceMethod(getJoinPointMatch(), null, ex);
			}
			throw ex;
		}
	}
第三次调用 invoke(this) 方法 拦截器链中第三个拦截器调用
// 实为  @AfterReturning 注解的方法拦截器
org.springframework.aop.framework.adapter.AfterReturningAdviceInterceptor.invoke (MethodInvocation mi) throws Throwable {
        //  再次调用 proceed 方法
		Object retVal = mi.proceed();
		// 在 proceed 方法执行中出现异常后 则直接抛出异常
		// 正常执行完后 则执行 正常逻辑
		this.advice.afterReturning(retVal, mi.getMethod(), mi.getArguments(), mi.getThis());
		return retVal;
	}
第四次调用 invoke(this) 方法 拦截器链中第四个拦截器调用
// 实为 @After 注解的方法拦截器
org.springframework.aop.aspectj.AspectJAfterAdvice.invoke (MethodInvocation mi) throws Throwable {
		try {
		//  再次调用 proceed 方法
			return mi.proceed();
		}
		// finally 代码块的出现 确定了目标方法是否正常 都会进行方法执行
		finally {
			invokeAdviceMethod(getJoinPointMatch(), null, null);
		}
	}
第五次调用 invoke(this) 方法 拦截器链中第五个拦截器调用
// 实为 @Before 注解的方法拦截器
org.springframework.aop.framework.adapter.MethodBeforeAdviceInterceptor.invoke (MethodInvocation mi) throws Throwable {
        //该 invoke 方法会先执行 方法前置通知逻辑
		this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis());
		// 然后再次执行 proceed 方法
		return mi.proceed();
	}
// 此时的 currentInterceptorIndex 指向的是拦截器链的最后一个 
// 此次会执行 if 代码块 并通过反射 执行目标方法. 并递归的向上结束方法的执行
proceed()  {
	if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
		return invokeJoinpoint();
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值