AOP实现

AOP实现(一)——Advice

在Spring1.2或之前的版本中,实现AOP的传统方式就是通过实现Spring的AOP API来定义Advice,并设置代理对象。Spring根据Adivce加入到业务流程的时机的不同,提供了四种不同的Advice:Before Advice、After Advice、Around Advice、Throw Advice。
1、Before Advice
顾名思义,Before Advice会在目标对象的方法执行之前被调用,您可以通过实现org.springframework.aop.MethodBeforeAdvice接口来实现Before Advice的逻辑,接口定义如下:

java 代码
  1. package org.springframework.aop;
  2. public interface MethodBeforeAdvice extends BeforeAdvice {
  3.    void before(Method method, Object[] args, Object target) throws Throwable;
  4. }

其中BeforeAdvice继承自Adivce接口,这两者都是标签接口,并没有定义任何具体的方法。before方法会在目标对象的指定方法执行之前被执行,在before方法种,你可以取得指定方法的Method实例、参数列表和目标对象,在before方法执行完后,目标对象上的方法将会执行,除非在before方法种抛出异常。
下面通过例子来说明Before Advice的使用方法。首先定义目标对象所要实现的接口:
java 代码
  1. package com.savage.aop
  2. public interface MessageSender {
  3.    void send(String message);
  4. }

接着实现MessageSender接口:
java 代码
  1. package com.savage.aop;
  2. public class HttpMessageSender implements MessageSender {
  3. public void send(String message) {
  4. System.out.println("Send Message[" + message + "] by http.");
  5. }
  6. }

OK,我们的业务代码实现完了,现在如果要在不改变我们的业务代码的前提下,在执行业务代码前要记录一些日志,这时就可以通过实现MethodBeforeAdvice接口来实现,如:
java 代码
  1. package com.savage.aop;
  2. import java.lang.reflect.Method;
  3. import org.springframework.aop.framework.MethodBeforeAdvice;
  4. public class LogBeforeAdvice implements MethodAdvice {
  5.    public void before(Method method, Object[] args, Object target) throws Throwable {
  6.       System.out.println("Log before " + method + " by LogBeforeAdvice.");
  7.    }
  8. }

然后再在XML进行如下定义:
xml 代码
 
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans    
  5. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">    
  6.   
  7.     <bean id="messageSenderImpl" class="com.savage.aop.HttpMessageSender"></bean>    
  8.       
  9.     <bean id="logBeforeAdvice" class="com.savage.aop.LogBeforeAdvice"></bean>    
  10.       
  11.     <bean id="messageSender" class="org.springframework.aop.framework.ProxyFactoryBean">    
  12.         <property name="proxyInterfaces" value="com.savage.aop.MessageSender"/>    
  13.         <property name="target" ref="messageSenderImpl"/>    
  14.         <property name="interceptorNames">    
  15.             <list>    
  16.                 <value>logBeforeAdvice</value>    
  17.             </list>    
  18.         </property>    
  19.     </bean>    
  20. </beans>   


这样我们就为MessageSender对象指定了Before Advice对象。在这里,我们分别定义了一个MessageSender对象(messageSenderImpl)和一个Before Advice对象(logBeforeAdvice),并定义了一个org.springframework.aop.framework.ProxyFactoryBean对象(messageSender),FactoryBean或ApplicationContext将使用ProxyFactoryBean来建立代理对象,在这里就是messageSenderImpl建立代理对象。在ProxyFactoryBean的定义中,proxyInterfaces属性指定了要代理的接口;target指定了要建立代理的目标对象;interceptorNames则指定了应用与指定接口上的Advices对象列表,spring将根据列表中定义的顺序在执行目标对象的方法前、后执行Advice中定义的方法。
现在我们写一个程序来验证下:
java 代码
  1. package com.savage.aop;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplication;
  4. public class AdviceDemo {
  5.    public void main(String[] args) {
  6.       ApplicationContext context = new ClassPathXmlApplicationContext("beans-config.xml");
  7.       MessageSender sender = (MessageSender)context.getBean("messageSender");
  8.       sender.send("message");
  9.   }
  10. }

执行结果:
Log before public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogBeforeAdvice.
Send Message[message] by http.

正如你所看到的,在执行 MessageSendersend 方法前先执行了 LogBeforeAdvice 的方法!在这个例子中,记录日志的代码并没有横切到我们的业务代码中, LogBeforeAdviceHttpMessageSender 彼此不知道对方的存在,而且我们的应用程序 AdviceDemoLogBeforeAdvice 的存在也是一无所知。假如有一天我们的应用程序不需要再业务代码执行前记录日志了,只需要修改 XML 文件中的定义,而不用更改 AdviceDemo 的代码:
xml 代码
  1. <bean id="messageSender" class="com.savage.aop.HttpMessageSender">bean>

2After Advice
After Advice 会在目标对象的方法执行完后执行,你可以通过实现 org.springframework.aop.AfterReturingAdvice 接口来实现 After Advice 的逻辑, AfterReturingAdvice 接口定义如下:
java 代码
  1. package org.springframework.aop;
  2. public interface AfterReturningAdvice {
  3.    void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable;
  4. }

afterReturning 方法中,你可以获得目标方法执行后的返回值、目标方法对象、目标方法的参数以及目标对象。
继续以上面的例子为例,如果要在 MessageSendersend 方法执行完后,要再记录日志,那么我们可以先实现 AfterReturningAdvice 接口:
java 代码
  1. package com.savage.aop;
  2. import org.springframework.aop;
  3. public LogAfterAdvice implements AfterReturningAdvice {
  4.    public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
  5.       System.out.println("Log after " + method + " by LogAfterAdvice.");
  6.    }
  7. }

然后在 XML 文件中指定 LogAfterAdvice 的实例:
xml 代码
 
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans    
  5. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">    
  6.   
  7.     <bean id="messageSenderImpl" class="com.savage.aop.HttpMessageSender"></bean>    
  8.       
  9.     <bean id="logBeforeAdvice" class="com.savage.aop.LogBeforeAdvice"></bean>    
  10.       
  11.     <bean id="messageSender" class="org.springframework.aop.framework.ProxyFactoryBean">    
  12.         <property name="proxyInterfaces" value="com.savage.aop.MessageSender"/>    
  13.         <property name="target" ref="messageSenderImpl"/>    
  14.         <property name="interceptorNames">    
  15.             <list>     
  16.                 <value>logAfterAdvice</value>  
  17.             </list>    
  18.         </property>    
  19.     </bean>    
  20. </beans>   


在前面 Before Advice 的基础上,我们为 MessageSender 再指定了一个 LogAfterAdvice 的服务。运行前面的 AdviceDemo ,结果如下:
Send Message[message] by http.
Log after public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogAfterAdvice.


3Around Advice
在上面的 LogAfterAdvice 例子中,我们通过指定 BeforeAdviceAfterReturingAdvice ,在 MessageSendersend 方法前后执行额外的业务。实际上,如果需要在业务代码执行前后增加额外的服务,你可以直接通过实现 org.aopalliance.intercept.MethodInterceptor 接口来达到这一目的, MethodInterceptor 定义如下:
java 代码
  1. package org.aopalliance.intercept;
  2. public interface MethodInterceptor {
  3.    public Object invoke(MethodInvocation methodInvocation) throws Throwable;
  4. }

例如:
java 代码
  1. package com.savage.aop;
  2. import org.aopalliance.intercept.MethodInterceptor;
  3. import org.aopalliance.intercept.MethodInvocation;
  4. public class LogAdvice implements MethodInterceptor {
  5.    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  6.       System.out.println("Log before " + methodInvocation.getMethod() + " by LogAdvice.");
  7.       Object retValue = methodInvocation.proceed();
  8.       System.out.println("Log after " + methodInvocation.getMethod() + " by LogAdvice.");
  9.       return retValue;
  10.    }
  11. }

正如上面所示,在 MethodInterceptor 中你得自行决定是否调用 MethodInvocationproceed() 方法来执行目标对象上的方法, proceed() 方法在执行完后会返回目标对象上方法的执行结果。
MethodInterceptorXML 文件中的定义如下:
xml 代码
 
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans    
  5. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">    
  6.   
  7.     <bean id="messageSenderImpl" class="com.savage.aop.HttpMessageSender"></bean>    
  8.       
  9.     <bean id="logAdvice" class="com.savage.aop.LogAdvice"></bean>    
  10.       
  11.     <bean id="messageSender" class="org.springframework.aop.framework.ProxyFactoryBean">  
  12.         <property id="proxyInterfaces" value="com.savage.aop.MessageSender"/>    
  13.         <property id="target" ref="messageSenderImpl"/>  
  14.         <property id="interceptorNames">  
  15.             <list>  
  16.                 <value>logAdvice</value>  
  17.             </list>  
  18.         </property>  
  19.     </bean>  
  20. </beans>  


Spring 在真正执行目标对象的方法前,会执行 interceptorNames 中执行的 Advice ,每个 Advice 在执行完自己的业务后,会调用 MethodInvocationproceed() 方法,将执行的主动权移交给下一个 Advice ,直到没有下一个 Advice 为止,在执行完目标对象的方法后, Spring 会再以相反的顺序一层层的返回。例如:
xml 代码
 
  1. <bean id="messageSender" class="org.springframework.aop.framework.ProxyFactoryBean">  
  2.     <property id="proxyInterfaces" value="com.savage.aop.MessageSender"/>    
  3.     <property id="target" ref="messageSenderImpl"/>  
  4.     <property id="interceptorNames">  
  5.         <list>  
  6.             <value>logBeforeAdvice</value>  
  7.             <value>logAdvice</value>  
  8.             <value>logAfterAdvice</value>  
  9.         </list>  
  10.     </property>  
  11. </bean>  


象上面这个例子, logBeforeAdvice 先会被执行,然后执行 logAdvice ,接着执行 logAfterAdvice ,最后又返回到了 logAdvice
现在我们把 LogAdvice 作一下简单的修改,增加一个 id 属性,用以在后面查看 Advice 的调用顺序:
java 代码
  1. package com.savage.aop;
  2. import org.aopalliance.intercept.MethodInterceptor;
  3. import org.aopalliance.intercept.MethodInvocation;
  4. public class LogAdvice implements MethodInterceptor {
  5.    private static int INSTANCE_NUM = 0;
  6.    private int id;
  7.    public LogAdvice() {
  8.       id = ++INSTANCE_NUM;
  9.    }
  10.    public Object invoke(MethodInvocation methodInvocation) throws Throwable {
  11.       System.out.println("Log before " + methodInvocation.getMethod() + " by LogAdvice[" + id + "].");
  12.       Object retValue = methodInvocation.proceed();
  13.       System.out.println("Log after " + methodInvocation.getMethod() + " by LogAdvice[" + id + "].");
  14.       return retValue;
  15.    }
  16. }

同时把 XML 中的定义改为:
xml 代码
 
  1. <?xml version="1.0" encoding="UTF-8"?>    
  2. <beans xmlns="http://www.springframework.org/schema/beans"    
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans    
  5. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">    
  6.   
  7.     <bean id="messageSenderImpl" class="com.savage.aop.HttpMessageSender"></bean>    
  8.       
  9.     <bean id="logBeforeAdvice" class="com.savage.aop.LogBeforeAdvice"></bean>    
  10.     <bean id="logAfterAdvice" class="com.savage.aop.LogAfterAdvice"></bean>    
  11.     <bean id="logAdvice1" class="com.savage.aop.LogAdvice"></bean>    
  12.     <bean id="logAdvice2" class="com.savage.aop.LogAdvice"></bean>    
  13.       
  14.     <bean id="messageSender" class="org.springframework.aop.framework.ProxyFactoryBean">  
  15.         <property id="proxyInterfaces" value="com.savage.aop.MessageSender"/>    
  16.         <property id="target" ref="messageSenderImpl"/>  
  17.         <property id="interceptorNames">  
  18.             <list>  
  19.                 <value>logBeforeAdvice</value>  
  20.                 <value>logAdvice1</value>  
  21.                 <value>logAfterAdvice</value>  
  22.                 <value>logAdvice2</value>  
  23.             </list>  
  24.         </property>  
  25.     </bean>  
  26. </beans>  


现在再执行 AdviceDemo ,得到如下结果:
Log before public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogBeforeAdvice.
Log before public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogAdvice[1].
Log before public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogAdvice[2].
Send Message[message] by http.
Log after public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogAdvice[2].
Log after public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogAfterAdvice.
Log after public abstract void com.savage.simplespring.bean.MessageSender.send(java.lang.String) by LogAdvice[1].

4
Throw Advice
如果想要在异常发生时执行某些业务,你可以通过实现 org.springframework.aop.ThrowsAdvice 接口,这是一个标签接口,没有定义任何方法,你可以在当中为每个你需要处理的异常类定义 afterThrowing 方法,当程序出现异常时, spring 会根据异常的类型调用对应的 afterThrowing 方法。 AfterThrowing 的格式如下:
java 代码
  1. afterThrowing([Method],[args],[target],subClassOfThrowable);


方括号 [] 中的参数为可选项,但方法中必须有 subClassOfThrowable ,且必须是 Throwable 的子类。
Spring 在调用完 afterThrowing 方法后,原先的异常会继续在程序中传播,如果象要终止程序对异常的处理,只能在 afterThrowing 方法中抛出其他异常。

 

AOP实现(二)——Spring 2.0中的AOP实现

Spring 2.0中,除了传统的通过实现AOP AIP的方式来实现Advice之外,还提供了两种更加简便的方式来实现Advice1)基于XML Schema的设置;2)基于Annotation的支持,采用这两种方式,Advice将不用实现特定的接口。现在让我们来看看如何使用这两种方式来分别实现Before AdviceAfter AdviceAround AdviceThrowing Advice
    一、Before Advice:基于XML Schema
当基于XML Schema实现Before Advice时,你的Advice类不用实现org.springframework.aop.MethodBeforeAdvice接口,例如:

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4.   
  5. public class LogBeforeAdvice {  
  6.     public void before(JoinPoint joinPoint) {  
  7.         System.out.println("Logging before " + joinPoint.getSignature().getName());  
  8.     }  
  9. }  



          before方法是在目标对象上的方法被执行前要执行的方法,before方法中的JoinPoint参数是可选项,你可以根据需要决定是否需要JoinPoint参数,通过JoinPoint对象,你可以获得目标对象(getTarget())、目标方法上的参数(getArgs())等信息。
     然后在XML中为目标对象指定LogBeforeAdvice代理:

xml 代码

 

 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.     http://www.springframework.org/schema/aop  
  8.     http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  9.     <bean id="messageSender" class="com.savage.aop.HttpMessageSender"></bean>  
  10.       
  11.     <bean id="logBeforeAdvice" class="com.savage.aop.LogBeforeAdvice"></bean>  
  12.       
  13.     <aop:config>  
  14.         <aop:aspect id="logBefore" ref="logBeforeAdvice">  
  15.             <aop:before pointcut="execution(* com.savage.aop.MessageSender.*(..))"
  16.                         method="before"/>  
  17.         </aop:aspect>  
  18.     </aop:config>  
  19. </beans>  



     如上所示,在Spring 2.0中要使用基于XML Sechma声明AOP的方式,需要在XML中加入aop的名称空间。当基于XML Sechma实现AOP时,所有的AOP都是在<aop:config></aop:config>标签中声明的,<aop:aspect></aop:aspect>用于定义Advice实例。<aop:before></aop:before>表示当前实例用于实现Before Advicepointcut属性用于指定pointcut表示式,上面的例子表示此Advice将应用于com.savage.aop.MessageSender接口中的任何方法;method属性表示Advice上要调用的方法。
     现在调用任何MessageSender接口上的方法之前都会执行LogBeforeAdvicebefore方法,例如:

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.springframework.context.ApplicationContext;  
  4. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  5.   
  6. public class AdviceDemo {  
  7.     public static void main(String[] args) {  
  8.         ApplicationContext context =
  9.                            new ClassPathXmlApplicationContext("beans-config.xml");  
  10.         MessageSender sender = (MessageSender)context.getBean("messageSender");  
  11.         sender.sendMessage("message");  
  12.     }  
  13. }  


     二、Before Advice:基于Annotation
        
使用Annotation来实现Advice,在XML文件上的定义要比基于XML Sechema的方法要简便的多,但在实现Before Advice类时,则需要使用到@Aspect@Before标识,并需要引入org.aspectj.lang.annotation包中的类。还以LogBeforeAdvice为例,LogBeforeAdvice类需要改为:

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.annotation.Aspect;  
  5. import org.aspectj.lang.annotation.Before;  
  6.   
  7. @Aspect  
  8. public class LogBeforeAdvice {  
  9.     @Before("execution(* com.savage.aop.MessageSender.*(..))")  
  10.     public void before(JoinPoint joinPoint) {  
  11.         System.out.println("Logging before " + joinPoint.getSignature().getName());  
  12.     }  
  13. }  



     如上所示,通过@Aspect将一个类声明为Aspect类,通过@Before将方法声明Before Advice,方法中的JoinPoint同样是可选的。然后在XML文件中做如下定义:

xml 代码

 

 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.     http://www.springframework.org/schema/aop  
  8.     http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  9.     <bean id="messageSender" class="com.savage.aop.HttpMessageSender"></bean>  
  10.       
  11.     <bean id="logBeforeAdvice" class="com.savage.aop.LogBeforeAdvice"></bean>  
  12.       
  13.     <aop:aspectj-autoproxy/>  
  14. </beans>  



     所有基于Annotation实现的Advice,在XML文件中都只要使用<aop:aspectj-autoproxy></aop:aspectj-autoproxy>进行设置就可以了,非常简单。

     三、After Advice:基于XML Sechma
        
Before Advice一样,基于XML Sechma实现After Returning Advice时,不再需要org.springframework.aop.AfterReturningAdvice接口:

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4.   
  5. public class LogAfterReturningAdvice {  
  6.     public void afterReturning(JoinPoint joinPoint) {  
  7.         System.out.println("Logging after " + joinPoint.getSignature().getName());  
  8.     }  
  9. }  



然后在XML中做如下设置:

xml 代码

 

 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.     http://www.springframework.org/schema/aop  
  8.     http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  9.     <bean id="messageSender" class="com.savage.aop.HttpMessageSender"></bean>  
  10.       
  11.     <bean id="logAfterReturningAdvice" 
  12.           class="com.savage.aop.LogAfterReturningAdvice"></bean>  
  13.       
  14.     <aop:config>  
  15.         <aop:aspect id="logAfterReturning" ref="logAfterReturningAdvice">  
  16.             <aop:after-returning   
  17.                 pointcut="execution(* com.savage.aop.MessageSender.*(..))"   
  18.                 method="logAfterReturning"/>  
  19.         </aop:aspect>  
  20.     </aop:config>  
  21. </beans>  



    四、After Advice:基于Annotation
       
Before Advice相似,使用@AfterReturning来表示After Returning Advice

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.annotation.Aspect;  
  5. import org.aspectj.lang.annotation.AfterReturning;  
  6.   
  7. @Aspect  
  8. public class AfterReturningAdvice {  
  9.     @AfterReturning(pointcut="execution(* com.savage.aop.MessageSender.*(..))",
  10.                     returning="retVal")  
  11.     public void afterReturning(JoinPoint joinPoint, Object retVal) {  
  12.         System.out.println("Logging after " + joinPoint.getSignature().getName());  
  13.     }  
  14. }  



     这里和Before Advice有点不同的是,在定义Poincut表示式时,多了一个returning属性,用于指定目标方法执行完后的返回值。
     XML文件中的设置与LogBeforeAdvice的相似(将logBeforeAdvice的定义改为logAfterReturning的定义),不再列举。

     五、Around Advice:基于XML Sechma
         
Spring 2.0中,Around Advice不用实现org.aoplliance.intercept.MethodInterceptor接口,但Advice的方法必须返回对象,并且必须定义一个ProceedingJoinPoint参数,例如:

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.ProceedingJoinPoint;  
  4.   
  5. public class LogAroundAdvice {  
  6.     public void invoke(ProceedingJoinPoint joinPoint) {  
  7.         System.out.println("Logging before " + joinPoint.getSignature().getName());  
  8.         Object retVal = joinPoint.proceed();  
  9.         System.out.println("Logging after " + joinPoint.getSignature().getName());  
  10.         return retVal;  
  11.     }  
  12. }  



XML中的设置如下:

xml 代码

 

 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.     http://www.springframework.org/schema/aop  
  8.     http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  9.     <bean id="messageSender" class="com.savage.aop.HttpMessageSender"></bean>  
  10.       
  11.     <bean id="logAroundAdvice" class="com.savage.aop.LogAroundAdvice"></bean>  
  12.       
  13.     <aop:config>  
  14.         <aop:aspect id="logAround" ref="logAroundAdvice">  
  15.             <aop:around   
  16.                 pointcut="execution(* com.savage.aop.MessageSender.*(..))"   
  17.                 method="invoke"/>  
  18.         </aop:aspect>  
  19.     </aop:config>  
  20. </beans>  



     六、Around Advice:基于Annotation
         
Before Advice相似,使用@Around来表示Around Advice

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.ProceedingJoinPoint;  
  4. import org.aspectj.lang.annotation.Aspect;  
  5. import org.aspectj.lang.annotation.Around;  
  6.   
  7. @Aspect  
  8. public class AfterReturningAdvice {  
  9.     @Around("execution(* com.savage.aop.MessageSender.*(..))")  
  10.     public void invoke(ProceedingJoinPoint joinPoint) {  
  11.         System.out.println("Logging before " + joinPoint.getSignature().getName());  
  12.         Object retVal = joinPoint.proceed();  
  13.         System.out.println("Logging after " + joinPoint.getSignature().getName());  
  14.         return retVal;  
  15.     }  
  16. }  



     XML文件中的设置与LogBeforeAdvice的相似(将logBeforeAdvice的定义改为logAroundAdvice的定义),不再列举。

     七、Throw Advice:基于XML Sechma
        
Spring 2.0中,Throw Advice不用实现org.springframework.aop.ThrowsAdvice接口,但Advice的方法必须定义Throwable(或其子类)参数,例如:

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4.   
  5. public class LogThrowingAdvice {  
  6.     public void afterThrowing (JoinPoint joinPoint, Throwable throwable) {  
  7.         System.out.println("Logging when throwing " + joinPoint.getSignature().getName());  
  8.     }  
  9. }  



XML的设置如下:

xml 代码

 

 
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
  6.     http://www.springframework.org/schema/beans/spring-beans-2.0.xsd  
  7.     http://www.springframework.org/schema/aop  
  8.     http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">  
  9.     <bean id="messageSender" class="com.savage.aop.HttpMessageSender"></bean>  
  10.       
  11.     <bean id="logThrowingAdvice" class="com.savage.aop.LogThrowingAdvice"></bean>  
  12.       
  13.     <aop:config>  
  14.         <aop:aspect id="logThrowing" ref="logThrowingAdvice">  
  15.             <aop:after-throwing   
  16.                 pointcut="execution(* com.savage.aop.MessageSender.*(..))"  
  17.                 throwing="throwable"  
  18.                 method="afterThrowing"/>  
  19.         </aop:aspect>  
  20.     </aop:config>  
  21. </beans>  



     在<aop:after-throwing></aop:after-throwing>中必须定义throwing属性,指定方法中的throwable参数。Spring将根据异常类型决定是否调用afterThrowing方法。

     八、Throw Advice:基于Annotation

java 代码

 

 
  1. package com.savage.aop;  
  2.   
  3. import org.aspectj.lang.JoinPoint;  
  4. import org.aspectj.lang.annotation.Aspect;  
  5. import org.aspectj.lang.annotation.AfterThrowing;  
  6.   
  7. @Aspect  
  8. public class AfterThrowingAdvice {  
  9.     @AfterThrowing(pointcut="execution(* com.savage.aop.MessageSender.*(..))",
  10.                    throwing="throwable")  
  11.     public void afterThrowing(JoinPoint joinPoint, Throwable throwable) {  
  12.         System.out.println("Logging when throwing "
  13.                            + joinPoint.getSignature().getName());  
  14.     }  
  15. }  


       XML文件中的设置与LogBeforeAdvice的相似(将logBeforeAdvice的定义改为logThrowingAdvice的定义),不再列举。

 

 

AOP实现(三)——Spring 2.0中Pointcut的定义

Spring 2.0中,Pointcut的定义包括两个部分:Pointcut表示式(expression)Pointcut签名(signature)。让我们先看看execution表示式的格式:

java 代码

 

  1. execution(modifier-pattern?
  2.           ret-type-pattern
  3.           declaring-type-pattern?
  4.           name-pattern(param-pattern)
  5.           throws-pattern?)


括号中各个pattern分别表示修饰符匹配(modifier-pattern?)、返回值匹配(ret-type-pattern)、类路径匹配(declaring-type-pattern?)、方法名匹配(name-pattern)、参数匹配((param-pattern))、异常类型匹配(throws-pattern?),其中后面跟着“?”的是可选项。
在各个pattern中可以使用“*”来表示匹配所有。在(param-pattern)中,可以指定具体的参数类型,多个参数间用“,”隔开,各个也可以用“*”来表示匹配任意类型的参数,如(String)表示匹配一个String参数的方法;(*,String)表示匹配有两个参数的方法,第一个参数可以是任意类型,而第二个参数是String类型;可以用(..)表示零个或多个任意参数。
现在来看看几个例子:
1execution(* *(..))
表示匹配所有方法
2execution(public * com. savage.service.UserService.*(..))
表示匹配com.savage.server.UserService中所有的公有方法
3execution(* com.savage.server..*.*(..))
表示匹配com.savage.server包及其子包下的所有方法
除了execution表示式外,还有withinthistargetargsPointcut表示式。一个Pointcut定义由Pointcut表示式和Pointcut签名组成,例如:

java 代码

 

  1. //Pointcut表示式
  2. @Pointcut("execution(* com.savage.aop.MessageSender.*(..))")
  3. //Point签名
  4. private void log(){}                             


然后要使用所定义的Pointcut时,可以指定Pointcut签名,如

java 代码

 

  1. @Before("og()")


上面的定义等同与:

java 代码

 

  1. @Before("execution(* com.savage.aop.MessageSender.*(..))")


Pointcut定义时,还可以使用&&||!运算,如:

java 代码

 

  1. @Pointcut("execution(* com.savage.aop.MessageSender.*(..))")
  2. private void logSender(){}
  3. @Pointcut("execution(* com.savage.aop.MessageReceiver.*(..))")
  4. private void logReceiver(){}
  5. @Pointcut("logSender() || logReceiver()")
  6. private void logMessage(){}


这个例子中,logMessage()将匹配任何MessageSenderMessageReceiver中的任何方法。
还可以将一些公用的Pointcut放到一个类中,以供整个应用程序使用,如:

java 代码

 

  1. package com.savage.aop;
  2. import org.aspectj.lang.annotation.*;
  3. public class Pointcuts {
  4.    @Pointcut("execution(* *Message(..))")
  5.    public void logMessage(){}
  6.    @Pointcut("execution(* *Attachment(..))")
  7.    public void logAttachment(){}
  8.    @Pointcut("execution(* *Service.*(..))")
  9.    public void auth(){}
  10. }


在使用这些Pointcut时,指定完整的类名加上Pointcut签名就可以了,如:

java 代码

 

  1. package com.savage.aop;
  2. import org.aspectj.lang.JoinPoint;
  3. import org.aspectj.lang.annotation.*;
  4. @Aspect
  5. public class LogBeforeAdvice {
  6.    @Before("com.sagage.aop.Pointcuts.logMessage()")
  7.    public void before(JoinPoint joinPoint) {
  8.       System.out.println("Logging before " + joinPoint.getSignature().getName());
  9.    }
  10. }


当基于XML Sechma实现Advice时,如果Pointcut需要被重用,可以使用<aop:pointcut></aop:pointcut>来声明Pointcut,然后在需要使用这个Pointcut的地方,用pointcut-ref引用就行了,如:

xml 代码

 

 
  1. <aop:config>  
  2.     <aop:pointcut id="log"   
  3.           expression="execution(* com.savage.simplespring.bean.MessageSender.*(..))"/>  
  4.     <aop:aspect id="logging" ref="logBeforeAdvice">  
  5.         <aop:before pointcut-ref="log" method="before"/>  
  6.         <aop:after-returning pointcut-ref="log" method="afterReturning"/>  
  7.     </aop:aspect>  
  8. </aop:config>  


 

转载于:https://www.cnblogs.com/plin2008/archive/2010/04/14/1712218.html

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值