先模拟一下SpringAop中的责任链
public interface MethodInvocation {
Object proceed() throws Throwable;
}
定义拦截器接口
public interface MethodInterceptor {
Object invoke(MethodInvocation methodInvocation) throws Throwable;
}
定义前置通知,在目标方法调用前执行通知
public class MethodBeforeAdviceInterceptor implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
System.out.println("I am BeforeAdvice");
return mi.proceed();
}
}
定义后置通知,在目标方法完成后执行通知
public class AspectJAfterAdvice implements MethodInterceptor {
@Override
public Object invoke(MethodInvocation mi) throws Throwable {
try {
return mi.proceed();
}
finally {
System.out.println("I am AfterAdvice");
}
}
}
中间类,拦截器链调用逻辑:
public class ReflectiveMethodInvocation implements MethodInvocation {
List<MethodInterceptor> methodInterceptors;
private int currentInterceptorIndex = -1;
public ReflectiveMethodInvocation(List<MethodInterceptor> methodInterceptors) {
this.methodInterceptors = methodInterceptors;
}
@Override
public Object proceed() throws Throwable {
if (currentInterceptorIndex == this.methodInterceptors.size() - 1) {
System.out.println("真正的目标方法");
return "目标方法执行";
}
MethodInterceptor methodInterceptor = this.methodInterceptors.get(++this.currentInterceptorIndex);
return methodInterceptor.invoke(this);
}
}
测试类:
public class Test {
public static void main(String[] args) throws Throwable {
AspectJAfterAdvice aspectJAfterAdvice = new AspectJAfterAdvice();
MethodBeforeAdviceInterceptor methodBeforeAdviceInterceptor = new MethodBeforeAdviceInterceptor();
List<MethodInterceptor> methodInterceptors = new ArrayList<>();
methodInterceptors.add(methodBeforeAdviceInterceptor);
methodInterceptors.add(aspectJAfterAdvice);
ReflectiveMethodInvocation reflectiveMethodInvocation = new ReflectiveMethodInvocation(methodInterceptors);
reflectiveMethodInvocation.proceed();
}
}
执行结果: