1. @Around
注解
@Around
是一种环绕通知(Around Advice),它允许你在目标方法执行前后都执行一些逻辑。这意味着你可以在方法调用之前、之后甚至在方法抛出异常时执行特定的逻辑。
示例
@Around("@annotation(myLock)")
public Object aroundAdvice(ProceedingJoinPoint joinPoint) throws Throwable {
// 前置逻辑
System.out.println("Before method execution");
// 执行目标方法
Object result = joinPoint.proceed();
// 后置逻辑
System.out.println("After method execution");
return result;
}
特点
- 灵活性高:可以在方法调用前后执行任意逻辑。
- 控制方法执行:可以决定是否继续执行目标方法(通过
proceed()
方法)。 - 捕获异常:可以在方法抛出异常时捕获并处理。
2. @Pointcut
注解
@Pointcut
用于定义切点(Pointcut),即确定哪些方法需要被拦截。切点表达式可以非常灵活,可以基于方法名、类名、注解等多种条件来定义。
示例
@Pointcut("execution(* com.example.service.*.*(..))")
public void serviceMethods() {
}
@Before("serviceMethods()")
public void beforeServiceMethods(JoinPoint joinPoint) {
System.out.println("Before service method execution");
}
@AfterReturning(pointcut = "serviceMethods()", returning = "result")
public void afterServiceMethods(JoinPoint joinPoint, Object result) {
System.out.println("After service method execution, result: " + result);
}
特点
- 定义切点