Spring深度解析-15、AOP拦截器链实现原理

本文详细探讨了Spring AOP中的拦截器链实现原理,从ReflectiveMethodInvocation的proceed方法出发,解释了拦截器如何按照顺序执行,并通过advised和advisorChainFactory了解拦截器链的构建和缓存过程。内容涵盖了拦截器链的匹配逻辑、前置、后置及异常增强的适配器和拦截器的工作方式。
摘要由CSDN通过智能技术生成

在上一篇章的学习中了解到AOP代理对象的执行过程,AOP中的代理对象有JDK代理与CGLIB代理两种方式,这两种代理对象在对目标对象的方法进行拦截,分别通过JdkDynamicAopProxy的invoke和DynamicAdvisedInterceptor的intercept来拦截。
这两种的原理是一致的:
1、先判断有没有拦截器链,如果没有,那么直接执行目标对象的方法
2、如果有拦截器链,则封装成ReflectiveMethodInvocation,执行proceed方法依次调用拦截器,然后返回目标方法执行的结果。
今天就来看看AOP的拦截器链是如何实现的。

拦截器链如何拦截

关于AOP拦截器链的实现,当然是通过ReflectiveMethodInvocation的proceed去了解。

public Object proceed() throws Throwable {
		//如果拦截器执行完了,就执行目标方法
		if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
			return invokeJoinpoint();
		}

//依次获取拦截器
		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;
			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.
			return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
		}
	}

拦截器链的调用是这样的:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值