Spring AOP + AspectJ Annotation Example

来源:互联网 发布:java线程 第四版 pdf 编辑:程序博客网 时间:2024/05/22 10:34

原文地址:http://www.mkyong.com/spring3/spring-aop-aspectj-annotation-example/

In this tutorial, we show you how to integrate AspectJ annotation with Spring AOP framework. In simple, Spring AOP + AspectJ allow you to intercept method easily.

Common AspectJ annotations :

  1. @Before – Run before the method execution
  2. @After – Run after the method returned a result
  3. @AfterReturning – Run after the method returned a result, intercept the returned result as well.
  4. @AfterThrowing – Run after the method throws an exception
  5. @Around – Run around the method execution, combine all three advices above.

    1. Directory Structure

    See directory structure of this example.

    directory structure of this example

    2. Project Dependencies

    To enable AspectJ, you need aspectjrt.jaraspectjweaver.jar and spring-aop.jar. See following Maven pom.xml file.

    AspectJ supported since Spring 2.0
    This example is using Spring 3, but the AspectJ features are supported since Spring 2.0.

    File : pom.xml

    [html] view plaincopy
    1. <project ...>  
    2.    
    3.     <properties>  
    4.         <spring.version>3.0.5.RELEASE</spring.version>  
    5.     </properties>  
    6.    
    7.     <dependencies>  
    8.    
    9.         <dependency>  
    10.             <groupId>org.springframework</groupId>  
    11.             <artifactId>spring-core</artifactId>  
    12.             <version>${spring.version}</version>  
    13.         </dependency>  
    14.    
    15.         <dependency>  
    16.             <groupId>org.springframework</groupId>  
    17.             <artifactId>spring-context</artifactId>  
    18.             <version>${spring.version}</version>  
    19.         </dependency>  
    20.    
    21.         <!-- Spring AOP + AspectJ -->  
    22.         <dependency>  
    23.             <groupId>org.springframework</groupId>  
    24.             <artifactId>spring-aop</artifactId>  
    25.             <version>${spring.version}</version>  
    26.         </dependency>  
    27.    
    28.         <dependency>  
    29.             <groupId>org.aspectj</groupId>  
    30.             <artifactId>aspectjrt</artifactId>  
    31.             <version>1.6.11</version>  
    32.         </dependency>  
    33.    
    34.         <dependency>  
    35.             <groupId>org.aspectj</groupId>  
    36.             <artifactId>aspectjweaver</artifactId>  
    37.             <version>1.6.11</version>  
    38.         </dependency>  
    39.    
    40.     </dependencies>  
    41. </project>  

    3. Spring Beans

    Normal bean, with few methods, later intercept it via AspectJ annotation.

    [java] view plaincopy
    1. package com.mkyong.customer.bo;  
    2.    
    3. public interface CustomerBo {  
    4.    
    5.     void addCustomer();  
    6.    
    7.     String addCustomerReturnValue();  
    8.    
    9.     void addCustomerThrowException() throws Exception;  
    10.    
    11.     void addCustomerAround(String name);  
    12. }  

    [java] view plaincopy
    1. package com.mkyong.customer.bo.impl;  
    2.    
    3. import com.mkyong.customer.bo.CustomerBo;  
    4.    
    5. public class CustomerBoImpl implements CustomerBo {  
    6.    
    7.     public void addCustomer(){  
    8.         System.out.println("addCustomer() is running ");  
    9.     }  
    10.    
    11.     public String addCustomerReturnValue(){  
    12.         System.out.println("addCustomerReturnValue() is running ");  
    13.         return "abc";  
    14.     }  
    15.    
    16.     public void addCustomerThrowException() throws Exception {  
    17.         System.out.println("addCustomerThrowException() is running ");  
    18.         throw new Exception("Generic Error");  
    19.     }  
    20.    
    21.     public void addCustomerAround(String name){  
    22.         System.out.println("addCustomerAround() is running, args : " + name);  
    23.     }  
    24. }  

    4. Enable AspectJ

    In Spring configuration file, put “<aop:aspectj-autoproxy />“, and define your Aspect (interceptor) and normal bean.

    File : Spring-Customer.xml

    [java] view plaincopy
    1. <beans xmlns="http://www.springframework.org/schema/beans"  
    2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    3.     xmlns:aop="http://www.springframework.org/schema/aop"  
    4.     xsi:schemaLocation="http://www.springframework.org/schema/beans  
    5.     http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
    6.     http://www.springframework.org/schema/aop   
    7.     http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">  
    8.    
    9.     <aop:aspectj-autoproxy />  
    10.    
    11.     <bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" />  
    12.    
    13.     <!-- Aspect -->  
    14.     <bean id="logAspect" class="com.mkyong.aspect.LoggingAspect" />  
    15.    
    16. </beans>  

    4. AspectJ @Before

    In below example, the logBefore() method will be executed before the execution of customerBo interface, addCustomer()method.

    Note
    AspectJ “pointcuts” is used to declare which method is going to intercept, and you should refer to this Spring AOP pointcuts guide for full list of supported pointcuts expressions.

    File : LoggingAspect.java
    [java] view plaincopy
    1. package com.mkyong.aspect;  
    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 LoggingAspect {  
    9.    
    10.     @Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")  
    11.     public void logBefore(JoinPoint joinPoint) {  
    12.    
    13.         System.out.println("logBefore() is running!");  
    14.         System.out.println("hijacked : " + joinPoint.getSignature().getName());  
    15.         System.out.println("******");  
    16.     }  
    17.    
    18. }  

    Run it(applicationContext.xml)
    [java] view plaincopy
    1. public static void main(String args[]){  
    2.     ApplicationContext appContext = new ClassPathXmlApplicationContext("applicationContext.xml");  
    3.     CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");  
    4.     customer.addCustomer();  
    5. }  

    5. AspectJ @After

    In below example, the logAfter() method will be executed after the execution of customerBo interface, addCustomer()method.

    File : LoggingAspect.java

    .
    [java] view plaincopy
    1. package com.mkyong.aspect;  
    2.    
    3. import org.aspectj.lang.JoinPoint;  
    4. import org.aspectj.lang.annotation.Aspect;  
    5. import org.aspectj.lang.annotation.After;  
    6.    
    7. @Aspect  
    8. public class LoggingAspect {  
    9.    
    10.     @After("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..))")  
    11.     public void logAfter(JoinPoint joinPoint) {  
    12.    
    13.         System.out.println("logAfter() is running!");  
    14.         System.out.println("hijacked : " + joinPoint.getSignature().getName());  
    15.         System.out.println("******");  
    16.    
    17.     }  
    18.    
    19. }  

    Run it
    [java] view plaincopy
    1. CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");  
    2. customer.addCustomer();  

    6. AspectJ @AfterReturning

    In below example, the logAfterReturning() method will be executed after the execution of customerBo interface,addCustomerReturnValue() method. In addition, you can intercept the returned value with the “returning” attribute.

    To intercept returned value, the value of the “returning” attribute (result) need to be same with the method parameter (result).

    File : LoggingAspect.java

    [java] view plaincopy
    1. package com.mkyong.aspect;  
    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 LoggingAspect {  
    9.    
    10.    @AfterReturning(  
    11.       pointcut = "execution(* com.mkyong.customer.bo.CustomerBo.addCustomerReturnValue(..))",  
    12.       returning= "result")  
    13.    public void logAfterReturning(JoinPoint joinPoint, Object result) {  
    14.    
    15.     System.out.println("logAfterReturning() is running!");  
    16.     System.out.println("hijacked : " + joinPoint.getSignature().getName());  
    17.     System.out.println("Method returned value is : " + result);  
    18.     System.out.println("******");  
    19.    
    20.    }  
    21.    
    22. }  

    Run it
    [java] view plaincopy
    1. CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");  
    2. customer.addCustomerReturnValue();  

    7. AspectJ @AfterReturning

    In below example, the logAfterThrowing() method will be executed if the customerBo interface,addCustomerThrowException() method is throwing an exception.

    File : LoggingAspect.java

    [java] view plaincopy
    1. package com.mkyong.aspect;  
    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 LoggingAspect {  
    9.    
    10.    @AfterThrowing(  
    11.       pointcut = "execution(* com.mkyong.customer.bo.CustomerBo.addCustomerThrowException(..))",  
    12.       throwing= "error")  
    13.     public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {  
    14.    
    15.     System.out.println("logAfterThrowing() is running!");  
    16.     System.out.println("hijacked : " + joinPoint.getSignature().getName());  
    17.     System.out.println("Exception : " + error);  
    18.     System.out.println("******");  
    19.    
    20.     }  
    21. }  

    Run it
    [java] view plaincopy
    1. CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");  
    2. customer.addCustomerThrowException();  

    Output
    [java] view plaincopy
    1. addCustomerThrowException() is running   
    2. logAfterThrowing() is running!  
    3. hijacked : addCustomerThrowException  
    4. Exception : java.lang.Exception: Generic Error  
    5. ******  
    6. Exception in thread "main" java.lang.Exception: Generic Error  
    7.     //...  

    8. AspectJ @Around

    In below example, the logAround() method will be executed before the customerBo interface, addCustomerAround()method, and you have to define the “joinPoint.proceed();” to control when should the interceptor return the control to the original addCustomerAround() method.

    File : LoggingAspect.java
    [java] view plaincopy
    1. package com.mkyong.aspect;  
    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 LoggingAspect {  
    9.    
    10.    @Around("execution(* com.mkyong.customer.bo.CustomerBo.addCustomerAround(..))")  
    11.    public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {  
    12.    
    13.     System.out.println("logAround() is running!");  
    14.     System.out.println("hijacked method : " + joinPoint.getSignature().getName());  
    15.     System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));  
    16.    
    17.     System.out.println("Around before is running!");  
    18.     joinPoint.proceed(); //continue on the intercepted method  
    19.     System.out.println("Around after is running!");  
    20.    
    21.     System.out.println("******");  
    22.    
    23.    }  
    24.    
    25. }  

    Run it
    [java] view plaincopy
    1. CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");  
    2. customer.addCustomerAround("mkyong");  

    Output
    [java] view plaincopy
    1. logAround() is running!  
    2. hijacked method : addCustomerAround  
    3. hijacked arguments : [mkyong]  
    4. Around before is running!  
    5. addCustomerAround() is running, args : mkyong  
    6. Around after is running!  
    7. ******  
0 0
原创粉丝点击