Spring 环绕通知

来源:互联网 发布:java file 新建文件夹 编辑:程序博客网 时间:2024/04/27 21:55

Spring 的环绕通知和前置通知,后置通知有着很大的区别,主要有两个重要的区别:1) 目标方法的调用由环绕通知决定,即你可以决定是否调用目标方法,而前置和后置通知是不能决定的,他们只是在方法的调用前后执行通知而已,即目标方法肯定是要执行的。2)环绕通知可以控制返回对象,即你可以返回一个与目标对象完全不同的返回值,虽然这很危险,但是你却可以办到。而后置方法是无法办到的,因为他是在目标方法返回值后调用。

      Spring 提供了Interceptor 接口来实现环绕通知。它只有一个invoke 方法,该方法接只接受MethodInvocation 参数。MethodInvocation 可以获得目标方法的参数,并可以通过proceed 方法调用原来的方法。代码如下:

      1)环绕通知

Java代码  收藏代码
  1. public class Around implements MethodInterceptor  
  2. {  
  3.     public Object invoke( MethodInvocation invocation)throws Throwable {  
  4.         System.out.println("Round.invoke()");  
  5.         System.out.println("Arguments:");  
  6.         Object[] args = invocation.getArguments();  
  7.         for(Object arg: args) {  
  8.             System.out.println(arg.getClass().getName() + ": " + arg);  
  9.         }  
  10.         System.out.println("Method name:" + invocation.getMethod().getName());  
  11.         //修改了目标方法返回值  
  12.         return invocation.proceed() + " in Round.invoke()";  
  13.     }  
  14. }  

     2)目标对象

Java代码  收藏代码
  1. public class Target implements Advice  
  2. {  
  3.     public String test(int i, String s, float f) {  
  4.         System.out.println("Target.test()");  
  5.         System.out.println("target: " + this);  
  6.         StringBuffer buf = new StringBuffer();  
  7.         buf.append( "i = " + i);  
  8.         buf.append( ", s = \"" + s + "\"");  
  9.         buf.append( ", f = " + f);  
  10.         return buf.toString();  
  11.     }  
  12. }  

     3)接口定义

Java代码  收藏代码
  1. public interface Advice  
  2. {  
  3.     String test(int i, String s, float f);  
  4. }  

     4)配置文件

Xml代码  收藏代码
  1. <beans>  
  2.     <bean id="around" class="spring.Around"/>  
  3.   
  4.       
  5.     <bean id="aop" class="org.springframework.aop.framework.ProxyFactoryBean">  
  6.         <property name="proxyInterfaces" value="spring.Advice" />  
  7.         <property name="interceptorNames">  
  8.             <list>  
  9.                 <value>around</value>  
  10.             </list>  
  11.         </property>  
  12.         <property name="target">  
  13.             <bean class="spring.Target" />  
  14.         </property>  
  15.     </bean>  
  16. </beans>  
原创粉丝点击