【SpringBoot】AOP 自定义注解的使用详解
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class MyAspect {
// 切入点表达式,这里以@MyAnnotation注解的方法为例
@Pointcut("@annotation(com.example.MyAnnotation)")
public void myPointcut() {
}
// 前置通知
@Before("myPointcut()")
public void beforeMethod(JoinPoint joinPoint) {
System.out.println("Before: " + joinPoint.getSignature().getName());
}
// 后置通知
@AfterReturning("myPointcut()")
public void afterReturningMethod(JoinPoint joinPoint) {
System.out.println("AfterReturning: " + joinPoint.getSignature().getName());
}
// 环绕通知
@Around("myPointcut()")
public Object aroundMethod(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
System.out.println("Around before: " + proceedingJoinPoint.getSignature().getName());
Object result = proceedingJoinPoint.proceed();
System.out.println("Around after: " + proceedingJoinPoint.getSignature().getName());
return result;
}
// 异常通知
@AfterThrowing(pointcut = "myPointcut()", throwing = "ex")
public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex) {
System.out.println("AfterThrowing from " + joinPoint.getSignature().getName() + ": " + ex.getMessage());
}
// 最终通知
@After("myPointcut()")
public void afterMethod(JoinPoint joinPoint) {
System.out.println("After: " + joinPoint.getSignature().getName());
}
}
这个示例代码定义了一个切面(Aspect),其中包含了五种通知方法:前置通知(@Before)、后置通知(@AfterReturning)、环绕通知(@Around)、异常通知(@AfterThrowing)和最终通知(@After)。切入点是所有带有自定义注解@MyAnnotation
的方法。这个例子展示了如何在SpringBoot应用中使用AOP来增强方法的调用。
评论已关闭