我有注释:
@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)")
则:
- 当在方法级别捕获时,
重试
会绑定(bind) - 当在类级别捕获时,
重试
为null。
当@Around
如下时@Around("@annotation(retry) || @within(retry)")
则:
- 当在方法级别捕获时,
重试
为null。 - 当在类级别捕获时,
重试
会绑定(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/