Spring AOP 无法双重绑定注解

2024-01-31

我有注释:

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Retry {

    int DEFAULT_RETRIES = 2;

    int times() default DEFAULT_RETRIES;
}

它可以在类级别使用:

@Retry(times = 5)
public class PersonServiceClass {

//...

    public void deletePerson(long id) {
        //...
    }
}

或方法级别(另一个类,不是 PersonServiceClass):

@Retry
public void deletePerson(long id) {
    //...
}

这个方面被这样的类捕获:

@Aspect
@Component
public class RetryInterceptor {

    @Around("@within(retry) || @annotation(retry)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint, Retry retry) throws Throwable {
        System.out.println("around - " + retry);
        System.out.println("joinpoint - " + proceedingJoinPoint);
        return aroundHandler(proceedingJoinPoint, retry);
    }

并且方面在方法或类级别上被正确捕获,但绑定有问题Retry注解。

When @Around如下:@Around("@within(retry) || @annotation(retry)") then:

  1. 当在方法级别捕获时retry is binded
  2. 当在班级水平上被抓住时retry is null.

When @Around如下@Around("@annotation(retry) || @within(retry)") then:

  1. 当在方法级别捕获时retry is null.
  2. 当在班级水平上被抓住时retryis binded.

Spring Boot 父版本 - 2.1.1.RELEASE


...现在你向我挑战:) 而我可以重现该问题 https://github.com/xerx593/soq54290855!

务实地说,我(会)像这样解决(d)它:

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class ExampleAspect {

  @Around("@within(retry)")
  public Object typeAspect(ProceedingJoinPoint joinPoint, Retry retry) throws Throwable {
    return commonAspect(joinPoint, retry);
  }

  @Around("@annotation(retry)")
  public Object methodAspect(ProceedingJoinPoint joinPoint, Retry retry) throws Throwable {
    return commonAspect(joinPoint, retry);
  }

  private Object commonAspect(ProceedingJoinPoint joinPoint, Retry retry) throws Throwable {
    System.out.println("Retry is :" + (retry == null ? "null" : retry.value()));
    // ... do your (common) stuff here
    return proceed;
  }

}

..欢迎! :-)

既然你已经有一个(共同的)aroundHandler()方法,归结为“为其引入 2 个公共立面/PCD”。

附加提示:重命名times()(如果它是该注释的唯一/主要属性):value()! ..那么你可以“只是”@Retry(100).

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring AOP 无法双重绑定注解 的相关文章

随机推荐