35 Spring AOP+AspectJ注解实例

作者: 笑Skr人啊 | 来源:发表于2017-08-24 15:01 被阅读56次

在本教程中,我们将向你展示如何将AspectJ注解集成到Spring AOP框架。在这个Spring AOP+ AspectJ 示例中,让您轻松实现拦截方法。

常见AspectJ的注解:

1 @Before – 方法执行前运行
2 @After – 运行在方法返回结果后
3 @AfterReturning – 运行在方法返回一个结果后,在拦截器返回结果。
4 @AfterThrowing – 运行方法在抛出异常后,
5 @Around – 围绕方法执行运行,结合以上这三个通知。

注意

Spring AOP 中没有 AspectJ 支持,请阅读 内置 Spring AOP 例子

1 公用类

package com.gp6.aop.aspectJ.annotation;

public interface CustomerBo {
    void addCustomer();
    
    String addCustomerReturnValue();
    
    void addCustomerThrowException() throws Exception;
    
    void addCustomerAround(String name);
}


package com.gp6.aop.aspectJ.annotation;

public class CustomerBoImpl implements CustomerBo {
    public void addCustomer(){
        System.out.println("addCustomer() is running ");
    }
    
    public String addCustomerReturnValue(){
        System.out.println("addCustomerReturnValue() is running ");
        return "abc";
    }
    
    public void addCustomerThrowException() throws Exception {
        System.out.println("addCustomerThrowException() is running ");
        throw new Exception("Generic Error");
    }
    
    public void addCustomerAround(String name){
        System.out.println("addCustomerAround() is running, args : " + name);
    }
}

2 公用配置文件----启用AspectJ

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/aop 
    http://www.springframework.org/schema/aop/spring-aop-3.0.xsd ">

    <!-- 在 Spring 配置文件,把“<aop:aspectj-autoproxy />”,并定义Aspect(拦截)和普通的bean -->
    <aop:aspectj-autoproxy />

    <bean id="customerBo" class="com.gp6.aop.aspectJ.annotation.CustomerBoImpl" />

    <!-- Aspect -->
    <bean id="logAspect" class="com.gp6.aop.aspectJ.annotation.LoggingAspect" />

</beans>

3. AspectJ @Before

在下面例子中,logBefore()方法将在 customerBo接口的 addCustomer()方法的执行之前被执行。
AspectJ的“切入点”是用来声明哪种方法将被拦截,应该参考Spring AOP切入点指南,支持切入点表达式的完整列表。

package com.gp6.aop.aspectJ.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {
    
    @Before("execution(* com.gp6.aop.aspectJ.annotation.CustomerBo.addCustomer(..))")
    public void logBefore(JoinPoint joinPoint) {

        System.out.println("logBefore() is running!================START");
        System.out.println("hijacked : " + joinPoint.getSignature().getName());
        System.out.println("logBefore() is running!================END");
    }
}



package com.gp6.aop.aspectJ.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) throws Exception {

        ApplicationContext appContext = new ClassPathXmlApplicationContext("com/gp6/aop/aspectJ/annotation/applicationContext.xml");

        CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
        customer.addCustomer();
        
        //customer.addCustomerReturnValue();
        
        //customer.addCustomerThrowException();
        
        //customer.addCustomerAround("gp6");

    }
}

运行

logBefore() is running!================START
hijacked : addCustomer
logBefore() is running!================END
addCustomer() is running 

4 . AspectJ @After

在下面例子中,logAfter()方法将在 customerBo 接口的 addCustomer()方法的执行之后执行。
File : LoggingAspect.java

package com.gp6.aop.aspectJ.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {
    @After("execution(* com.gp6.aop.aspectJ.annotation.CustomerBo.addCustomer(..))")
    public void logAfter(JoinPoint joinPoint) {

        System.out.println("logAfter() is running!================START");
        System.out.println("hijacked : " + joinPoint.getSignature().getName());
        System.out.println("logAfter() is running!================END");
    }
}


运行

addCustomer() is running 
logAfter() is running!================START
hijacked : addCustomer
logAfter() is running!================END

5 . AspectJ @AfterReturning

在下面例子中,logAfterReturning()方法将在 customerBo 接口的addCustomerReturnValue()方法执行之后执行。此外,还可以截取返回的值使用“returning”属性。

要截取返回的值,对“returning”属性(结果)的值必须用相同的方法参数(结果)。
File : LoggingAspect.java


package com.gp6.aop.aspectJ.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {
    @AfterReturning(pointcut = "execution(* com.gp6.aop.aspectJ.annotation.CustomerBo.addCustomerReturnValue(..))", returning= "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {

        System.out.println("logAfterReturning() is running!================START");
        System.out.println("hijacked : " + joinPoint.getSignature().getName());
        System.out.println("Method returned value is : " + result);
        System.out.println("logAfterReturning() is running!================END");
    }
}

package com.gp6.aop.aspectJ.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) throws Exception {

        ApplicationContext appContext = new ClassPathXmlApplicationContext("com/gp6/aop/aspectJ/annotation/applicationContext.xml");

        CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
        //customer.addCustomer();
        
        customer.addCustomerReturnValue();
        
        //customer.addCustomerThrowException();
        
        //customer.addCustomerAround("gp6");

    }
}


运行

addCustomerReturnValue() is running 
logAfterReturning() is running!================START
hijacked : addCustomerReturnValue
Method returned value is : abc
logAfterReturning() is running!================END

6. AspectJ @AfterThrowing

在下面的例子中,如果 customerBo 接口的addCustomerThrowException()方法抛出异常logAfterThrowing()方法将被执行。
File : LoggingAspect.java

package com.gp6.aop.aspectJ.annotation;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {
    @AfterThrowing(pointcut = "execution(* com.gp6.aop.aspectJ.annotation.CustomerBo.addCustomerThrowException(..))",throwing= "error")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable error) {
        System.out.println("logAfterThrowing() is running!================Start");
        System.out.println("hijacked : " + joinPoint.getSignature().getName());
        System.out.println("Exception : " + error);
        System.out.println("logAfterThrowing() is running!================END");

    }
}


package com.gp6.aop.aspectJ.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) throws Exception {

        ApplicationContext appContext = new ClassPathXmlApplicationContext("com/gp6/aop/aspectJ/annotation/applicationContext.xml");

        CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
        //customer.addCustomer();
        
        //customer.addCustomerReturnValue();
        
        customer.addCustomerThrowException();
        
        //customer.addCustomerAround("gp6");

    }
}

运行

addCustomerThrowException() is running 
logAfterThrowing() is running!================Start
hijacked : addCustomerThrowException
Exception : java.lang.Exception: Generic Error
logAfterThrowing() is running!================END
Exception in thread "main" java.lang.Exception: Generic Error
    at com.gp6.aop.aspectJ.annotation.CustomerBoImpl.addCustomerThrowException(CustomerBoImpl.java:15)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:318)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.springframework.aop.aspectj.AspectJAfterThrowingAdvice.invoke(AspectJAfterThrowingAdvice.java:55)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:90)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy5.addCustomerThrowException(Unknown Source)
    at com.gp6.aop.aspectJ.annotation.Test.main(Test.java:16)



7 . AspectJ @Around

在下面例子中,logAround()方法将在customerBo接口的addCustomerAround()方法执行之前执行, 必须定义“joinPoint.proceed();” 控制何时拦截器返回控制到原来的addCustomerAround()方法。

File : LoggingAspect.java


package com.gp6.aop.aspectJ.annotation;

import java.util.Arrays;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class LoggingAspect {
    @Around("execution(* com.gp6.aop.aspectJ.annotation.CustomerBo.addCustomerAround(..))")
       public void logAround(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("logAround() is running!================START");
        System.out.println("hijacked method : " + joinPoint.getSignature().getName());
        System.out.println("hijacked arguments : " + Arrays.toString(joinPoint.getArgs()));
            
        System.out.println("Around before is running!================START");
        joinPoint.proceed(); //continue on the intercepted method
        System.out.println("Around after is running!================START");
            
        System.out.println("******");

       }
}

package com.gp6.aop.aspectJ.annotation;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Test {
    public static void main(String[] args) throws Exception {

        ApplicationContext appContext = new ClassPathXmlApplicationContext("com/gp6/aop/aspectJ/annotation/applicationContext.xml");

        CustomerBo customer = (CustomerBo) appContext.getBean("customerBo");
        //customer.addCustomer();
        
        //customer.addCustomerReturnValue();
        
        //customer.addCustomerThrowException();
        
        customer.addCustomerAround("gp6");

    }
}


运行

logAround() is running!================START
hijacked method : addCustomerAround
hijacked arguments : [gp6]
Around before is running!================START
addCustomerAround() is running, args : gp6
Around after is running!================START
******
总结

建议采用最少 AspectJ 注解。这是关于Spring AspectJ 的一篇相当长的文章。

相关文章

网友评论

    本文标题:35 Spring AOP+AspectJ注解实例

    本文链接:https://www.haomeiwen.com/subject/vmledxtx.html