java - Spring AOP 无法双重绑定(bind)注解

标签 java spring aspectj spring-aop

我有注释:

@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);
    }

在方法或类级别上正确捕获了方面,但绑定(bind) Retry 注释时出现问题。

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

  1. 当在方法级别捕获时,重试绑定(bind)
  2. 当在类级别捕获时,重试null

@Around如下时@Around("@annotation(retry) || @within(retry)")则:

  1. 当在方法级别捕获时,重试null
  2. 当在类级别捕获时,重试绑定(bind)

Spring Boot 父版本 - 2.1.1.RELEASE

最佳答案

...现在你向我发起挑战:) 和我 could reproduce the issue !

实际上,我(会)像这样解决(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 个公共(public)外观/PCD”。

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

关于java - Spring AOP 无法双重绑定(bind)注解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54290855/

相关文章:

java - Autowiring 同一类的两个不同的bean

在 Spring 应用程序中找不到 CSS 文件

Java:隐式类型转换,或隐式 toString() 调用

java.util.Map$Entry 未解析

java - 如何跳过格式正确性检查 XML

java - 不是封闭类错误

java - 禁用 java ant 生成的警告

javascript - Spring Boot 静态资源

java - 确定哪个方法触发了一个方面

java - Maven 的 AspectJ 模块依赖 - 如何使用依赖模块的类型间声明方法