在上一篇章的学习中了解到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);
}
}
拦截器链的调用是这样的: