【Spring Aop】aspectj使用xml配置和注解两种方式的对比

227 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第5天,点击查看活动详情

在maven项目中使用aspectj的基础配置: 要在在maven工厂中引入aspectj的依赖:

 <dependency>  
     <groupId>org.aspectj</groupId>  
     <artifactId>aspectjweaver</artifactId>  
     <version>1.9.9.1</version>  
 </dependency>

使用xml配置

  1. 切入点定位<aop:pointcut id="ServicePointCut" expression="execution(* com..service..*(..))"/>
  2. 注册切面组件
  3. 在切面组件中写通知方法(Before, After, Around, AfterReturning, AfterThrowing)
  4. 使用aspect标签建立练习

切面组件和其中的几个方法如下:

@Component  
public class CustomAspect {  
    public void method1(){  
        System.out.println("hello before...");  
    }  
    public void method2(){  
        System.out.println("bye after...");  
    }  
    public Object method3(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {  
  
        System.out.println("around before");  
        Object proceed = proceedingJoinPoint.proceed();  
        System.out.println("around after");  
        return proceed;  
    }  
  
    public void method4(Object result){  
        System.out.println("return after is :"+result);  
    }  
  
    public void method5(Exception exception){  
        System.out.println("get a exception: "+exception.getMessage());  
    }  
}

这些方法是用于增强委托类的切入点方法的.

接下来在xml中配置aspect, 将切入点和增强方法一一对应.

<aop:config>  
    <aop:pointcut id="ServicePointCut" expression="execution(* com..service..*(..))"/>  
    <aop:aspect ref="customAspect">  
        <aop:before method="method1" pointcut-ref="ServicePointCut"/>  
        <aop:after method="method2" pointcut-ref="ServicePointCut"/>  
        <aop:around method="method3" pointcut-ref="ServicePointCut"/>  
        <aop:after-returning method="method4" pointcut-ref="ServicePointCut" returning="result"/>  
        <aop:after-throwing method="method5" pointcut-ref="ServicePointCut" throwing="exception"/>  
  
    </aop:aspect>  
</aop:config>

使用注解

整体的流程基本和xml配置一致, 只是将配置过程用注解封装了. 不用再写<aop:config>标签

整个流程是:

  1. 在配置类上打开注解开关
  2. 在切入点方法上使用注解@Pointcut, 或者在切面组件类中添加一个表示切入点的方法, @Pointcut注解放在该方法上, 切入点id为该方法名, 注解value属性中写切入点表达式
  3. 指定切面组件, 使用@Aspect
  4. 在切面组件的不同方法上使用通知注解@Before @After @Around @AfterReturning @AfterThrowing , 注解里放之前注册的切入点方法名或者直接写excution切入点表达式
 @Component  
 @Aspect  
 public class CustomAspect {  

     @Pointcut("execution(* com..service..*(..))")  
     public void servicePointcut(){}  

     //@Before(value = "execution(* com..service..*(..))")  
     @Before("execution(* com..service..*(..))")  
     public void method1() {  
         System.out.println("hello");  
     }  
       
     @After(value = "servicePointcut()") //引用切入点方法名的时候有一对括号  
     public void method2() {  
         System.out.println("world");  
     }  
}

注解和xml标签两者之间的关系

我画了一张图表示aop标签做的事情, 分析这个过程中的各种要素, 加深记忆:

aop的aspectj.drawio.png