aspectj语法

aspectj语法

AspectJ 是一种面向方面编程(AOP)的扩展,它允许开发者以模块化的方式处理横切关注点(cross-cutting concerns),如日志记录、事务管理、安全控制等。以下是对 AspectJ 语法的基本介绍:

1. 基本概念

  • 连接点(Join point):在程序执行过程中能够插入切面(aspect)的一个点。例如,方法调用或异常抛出都是连接点。
  • 切入点(Pointcut):一个表达式,用于匹配特定的连接点。切入点定义了哪些连接点将被增强(advice)。
  • 通知(Advice):在特定连接点上执行的代码片段。AspectJ 支持多种类型的通知,包括前置通知(before)、后置通知(after returning)、环绕通知(around)等。
  • 切面(Aspect):切面是包含切入点和通知的模块化单元。它将横切关注点封装起来,以便与业务逻辑分离。

2. 切面定义

使用 @Aspect 注解定义一个切面类。

import org.aspectj.lang.annotation.Aspect; @Aspect public class LoggingAspect { // 切面和通知的定义将在这里进行 }

3. 定义切入点

使用 @Pointcut 注解定义一个切入点表达式。

import org.aspectj.lang.annotation.Pointcut; @Aspect public class LoggingAspect { // 定义一个名为 allMethods 的切入点,匹配所有方法的执行 @Pointcut("execution(* *(..))") public void allMethods() {} }

4. 定义通知

前置通知(Before Advice)

在目标方法执行之前执行。

import org.aspectj.lang.annotation.Before; @Aspect public class LoggingAspect { @Pointcut("execution(* *(..))") public void allMethods() {} @Before("allMethods()") public void logBefore() { System.out.println("Executing method: " + thisJoinPoint.getSignature()); } }

后置通知(After Returning Advice)

在目标方法成功执行后执行。

import org.aspectj.lang.annotation.AfterReturning; @Aspect public class LoggingAspect { @Pointcut("execution(* *(..))") public void allMethods() {} @AfterReturning(pointcut = "allMethods()", returning = "result") public void logAfterReturning(Object result) { System.out.println("Method executed with result: " + result); } }

异常通知(After Throwing Advice)

在目标方法抛出异常时执行。

import org.aspectj.lang.annotation.AfterThrowing; @Aspect public class LoggingAspect { @Pointcut("execution(* *(..))") public void allMethods() {} @AfterThrowing(pointcut = "allMethods()", throwing = "exception") public void logAfterThrowing(Throwable exception) { System.out.println("Exception thrown: " + exception); } }

环绕通知(Around Advice)

在目标方法执行前后都执行,并且可以决定是否继续执行目标方法。

import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; @Aspect public class LoggingAspect { @Pointcut("execution(* *(..))") public void allMethods() {} @Around("allMethods()") public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable { System.out.println("Before executing method: " + joinPoint.getSignature()); Object result = joinPoint.proceed(); // 执行目标方法 System.out.println("After executing method: " + joinPoint.getSignature()); return result; } }

5. 使用 XML 配置(可选)

虽然注解配置非常常见和方便,但你也可以通过 XML 文件来配置 AspectJ 切面。

<aop:config> <aop:aspect id="loggingAspect" ref="loggingAspectBean"> <aop:pointcut id="allMethods" expression="execution(* *(..))"/> <aop:before method="logBefore" pointcut-ref="allMethods"/>