spring-aop有四种常用的advice类型,分别是在方法执行前执行的逻辑, 在方法返回前执行的逻辑, 在方法抛出异常时执行的逻辑以及在方法运行的过程中执行的逻辑(其实前面三种只是最后一种的特殊实现)。使用学习可以看链接:http://www.mkyong.com/spring/spring-aop-examples-advice/. 下面我们就来看看在方法执行前执行的逻辑是如何实现的。
其实spring实现aop是典型的动态代理加责任链模式,它是对目标对象生成一个代理对象, 在代理对象中,将切面逻辑加入。请看ReflectiveMethodInvocation的proceed()方法。
public Object proceed() throws Throwable {
// We start with an index of -1 and increment early.
<span style="white-space:pre"> </span>// 如果拦截器执行都已经循环过了,则执行业务逻辑
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;
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.
return ((MethodInterceptor) interceptorOrInterceptionAdvice).invoke(this);
}
}
从代码中可以看出,是典型的责任链模式。
我们再看看在方法执行前执行的逻辑是如何实现的:
看类MethodBeforeAdviceInterceptor:
public Object invoke(MethodInvocation mi) throws Throwable {
this.advice.before(mi.getMethod(), mi.getArguments(), mi.getThis() );
return mi.proceed();
}
可以看出, 它是在业务逻辑执行前执行advice的逻辑。