JoinPoint连接点:程序执行过程中明确的点,简单的来说就是Java程序执行过程中的方法。
JoinPoint接口图:
JoinPoint通过抽象实现成为一个个的Method,在执行每个JoinPoint所代表的Method中,会执行对应的Advice(参考博客Spring Aop源码学习--Advice通知)。
JoinPoint接口提供的方法
public interface Joinpoint {
//在实现中完成Method及Advice的执行
Object proceed() throws Throwable;
Object getThis();
AccessibleObject getStaticPart();
}
在JoinPoint的实现类ReflectiveMethodInvocation中实现了方法proceed()。
@Override
public Object proceed() throws Throwable {
//interceptorsAndDynamicMethodMatchers所有同志的链表
if (this.currentInterceptorIndex == this.interceptorsAndDynamicMethodMatchers.size() - 1) {
//如果所有的advice都已经进行处理就可以递归执行方法了
return invokeJoinpoint();
}
//每次获取一个advice
Object interceptorOrInterceptionAdvice =
this.interceptorsAndDynamicMethodMatchers.get(++this.currentInterceptorIndex);
if (interceptorOrInterceptionAdvice instanceof InterceptorAndDynamicMethodMatcher) {
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 {
//在调用的Advice的invoke方法时会递归调用proceed方法
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
在interceptorsAndDynamicMethodMatchers中包含了需要切入某个方法所有的Advice通知,通过不断的递归调用完成所有的Advice和Method执行顺序的预处理。
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
//执行mi.proceed执行先执行BeforeAdvice
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
return mi.proceed();
}
当链表中所有的Advice通知都被处理执行开始执行
invokeJoinpoint方法,来进行对目标方法的执行。
@Override
protected Object invokeJoinpoint() throws Throwable {
if (this.publicMethod) {
return this.methodProxy.invoke(this.target, this.arguments);
}
else {
return super.invokeJoinpoint();
}
}