`
javahigh1
  • 浏览: 1224477 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

Spring学习笔记:关于Interceptor

 
阅读更多

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

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

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

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

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

在以上四种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;
}
}

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

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics