@Around() 和 @Pointcut()注解的区别

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);
}
特点
  • 定义切点
`@Around("pointcut(requestLimiterValidate)")` 是一种Java注解,通常在AOP(面向切面编程)中使用,特别是Spring AOP框架下。这里的`around`通知类型表示对目标方法执行前后都有额外的行为发生。 `pointcut(requestLimiterValidate)` 是一个点切面(PointCut),它是AOP的核心概念,定义了一组匹配某种特定条件的方法,这些方法被称为通知(Advice)。在这个上下文中,`requestLimiterValidate`是一个字符串表达式或者是实现了`org.springframework.aop.Pointcut`接口的自定义切点定义,它定义了一个拦截器的目标范围,即哪些方法应该被这个`around`通知所包围。 简单来说,当你在某个方法上应用这个`@Around`注解,并传入`requestLimiterValidate`作为切点,那么在该方法执行之前(前置通知)之后(后置通知),都会执行一个名为`requestLimiterValidate`的逻辑,可能是检查请求是否满足限制(例如频率限制、并发限制等)、事务管理、日志记录或者安全验证等功能。 举个例子,你可能会在一个高并发环境下使用它来确保每个用户的请求次数不超过限制,或者在API调用前检查用户权限: ```java @Aspect @Component public class RequestLimitingAspect { @Around("execution(* com.example.service.*(..)) && args(user, limit)") public Object validateRequestLimit(ProceedingJoinPoint joinPoint, String user, int limit) throws Throwable { // 在这里执行请求限制逻辑 if (isRequestExceeded(user, limit)) { throw new RateLimitedException(); } // 执行原方法 Object result = joinPoint.proceed(); // 后置行为(可选) recordRequestStats(user); return result; } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值