spring

spring aop中的通知怎么编写

小樊
81
2024-09-02 05:50:51
栏目: 编程语言

在 Spring AOP 中,通知(Advice)是在目标方法执行前、后或出现异常时执行的代码。要编写一个通知,你需要创建一个类并实现相应的接口。以下是五种不同类型的通知及其实现方式:

  1. 前置通知(Before Advice):在目标方法执行前执行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

@Aspect
public class BeforeAdvice {
    @Before("execution(* com.example.service.*.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        System.out.println("前置通知:目标方法 " + joinPoint.getSignature().getName() + " 即将执行");
    }
}
  1. 后置通知(After Advice):在目标方法执行后执行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AfterAdvice {
    @After("execution(* com.example.service.*.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        System.out.println("后置通知:目标方法 " + joinPoint.getSignature().getName() + " 已执行完毕");
    }
}
  1. 返回通知(AfterReturning Advice):在目标方法正常返回后执行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AfterReturningAdvice {
    @AfterReturning("execution(* com.example.service.*.*(..))")
    public void afterReturningMethod(JoinPoint joinPoint) {
        System.out.println("返回通知:目标方法 " + joinPoint.getSignature().getName() + " 已正常返回");
    }
}
  1. 异常通知(AfterThrowing Advice):在目标方法抛出异常后执行的通知。
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AfterThrowingAdvice {
    @AfterThrowing("execution(* com.example.service.*.*(..))")
    public void afterThrowingMethod(JoinPoint joinPoint) {
        System.out.println("异常通知:目标方法 " + joinPoint.getSignature().getName() + " 发生异常");
    }
}
  1. 环绕通知(Around Advice):在目标方法执行前后都执行的通知。
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;

@Aspect
public class AroundAdvice {
    @Around("execution(* com.example.service.*.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) throws Throwable {
        System.out.println("环绕通知:目标方法 " + joinPoint.getSignature().getName() + " 即将执行");
        Object result = joinPoint.proceed();
        System.out.println("环绕通知:目标方法 " + joinPoint.getSignature().getName() + " 已执行完毕");
        return result;
    }
}

注意:在实际项目中,你可能需要根据需求调整切点表达式(如 execution(* com.example.service.*.*(..)))以匹配你的目标方法。同时,确保你的 Aspect 类被 Spring 容器管理,例如通过添加 @Component 注解。

0
看了该问题的人还看了