MethodInterceptor

咱们知道在Spring中一共提供了四种Advice用来支持对方法调用时施加的不一样行为.它们包括:

BeforeAdvice:具体接口:MethodBeforeAdvice 在目标方法调用以前调用的Advice java

AfterAdvice:具体接口:AfterReturningAdvice 在目标方法调用并返回以后调用的Advice spring

AroundAdvice:具休接口:MethodInterceptor 在目标方法的整个执行先后有效,而且有能力控制目标方法的执行 ui

ThrowsAdvice:具体接口:ThrowsAdvice 在目标方法抛出异常时调用的Advice spa

在以上四种Advice中最为特别的就是MethodInterceptor:方法拦截器.它的特别之处在于:首先他所在的包并不Srping中的包而是:org.aopalliance.intercept包.即MethodInterceptor实现了AOP联盟接口,这一点保证了它较之其余的Advice更具备通用性,由于它能够在任何基于AOP联盟接口实现的AOP系统中使用.第二点也就是其最为突出的一点就是它所具备的其余Advice所不能匹敌的功能:在目标方法的整个执行先后有效,而且有能力控制目标方法的执行!如下是一段具体代码(引自Spring in Action iist3.5.) 接口

package com.springinaction.chapter03.store;
import java.util.HashSet;
import java.util.Set;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
public class OnePerCustomerInterceptor implements MethodInterceptor {
private Set customers = new HashSet();
public Object invoke(MethodInvocation invocation)
throws Throwable {
Customer customer = (Customer) invocation.getArguments()[0];
if (customers.contains(customer)) {
throw new KwikEMartException("One per customer.");
}
Object squishee = invocation.proceed(); //调用目标方法
customers.add(customer);
return squishee;
}
}
get

在MethodInterceptor中有一个invoke方法,它们有一个MethodInvocation参数invocation,MethodInterceptor是能经过invocation的proceed方法来执行目标方法的.在显式地调用这个方法时,咱们能够在其以前和以后作一些相关操做,实现beforeAdvice和AfterAdvice的功能. io

相关文章
相关标签/搜索