spring-aop之MethodBeforeAdvice实现

        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的逻辑。 

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值