返回

Spring AOP 常见注解的魅力之旅

后端

Spring AOP 常见注解

Spring AOP 提供了五个常用的注解:@Before、@After、@Around、@AfterReturning 和 @AfterThrowing,每个注解都有其独特的用途和执行顺序。

  • @Before :在目标方法执行之前执行。
  • @After :在目标方法执行之后执行,无论方法是否成功执行。
  • @Around :在目标方法执行之前和之后都执行,并且可以决定是否继续执行目标方法。
  • @AfterReturning :在目标方法成功执行之后执行。
  • @AfterThrowing :在目标方法抛出异常之后执行。

Spring AOP 执行顺序

Spring AOP 注解的执行顺序遵循以下规则:

  1. @Before 注解首先执行。
  2. @Around 注解其次执行。
  3. 目标方法执行。
  4. @AfterReturning 或 @AfterThrowing 注解执行,具体取决于目标方法是否成功执行。
  5. @After 注解最后执行。

需要注意的是,@Around 注解可以决定是否继续执行目标方法。如果 @Around 注解中调用了 proceed() 方法,则目标方法将继续执行;否则,目标方法将不会执行。

Spring AOP 注解示例

以下是一个使用 Spring AOP 注解的示例:

@Aspect
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(JoinPoint joinPoint) {
        System.out.println("Before method: " + joinPoint.getSignature().getName());
    }

    @After("execution(* com.example.service.*.*(..))")
    public void logAfter(JoinPoint joinPoint) {
        System.out.println("After method: " + joinPoint.getSignature().getName());
    }

    @Around("execution(* com.example.service.*.*(..))")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("Around method: " + joinPoint.getSignature().getName());
        try {
            Object result = joinPoint.proceed();
            System.out.println("Around method: " + joinPoint.getSignature().getName() + " returned: " + result);
            return result;
        } catch (Throwable e) {
            System.out.println("Around method: " + joinPoint.getSignature().getName() + " threw exception: " + e);
            throw e;
        }
    }

    @AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
    public void logAfterReturning(JoinPoint joinPoint, Object result) {
        System.out.println("After returning method: " + joinPoint.getSignature().getName() + ", result: " + result);
    }

    @AfterThrowing(pointcut = "execution(* com.example.service.*.*(..))", throwing = "e")
    public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
        System.out.println("After throwing method: " + joinPoint.getSignature().getName() + ", exception: " + e);
    }
}

总结

Spring AOP 注解是 Spring 框架提供的一种强大的工具,它允许我们以一种非侵入式的方式在程序中添加横切关注点。Spring AOP 提供了五个常用的注解:@Before、@After、@Around、@AfterReturning 和 @AfterThrowing,每个注解都有其独特的用途和执行顺序。理解 Spring AOP 注解及其执行顺序可以帮助我们更好地理解和使用 Spring AOP。