AspectJ 如何将 @annotation 建议表达式与注释匹配,即使表达式处于不同的大小写(小写)?

问题描述 投票:0回答:1
@Auditable(value=1)
public ResponseEntity upload(@RequestParam file){
    // Code
}

此代码使用下面给出的 @Auditable 注释:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Auditable {
    Integer value() default 0;
}

我有如下方面

@Before("@annotation(auditable)")
public void audit(Integer auditable) {
  AuditCode code = auditable;
  // ...
}

在上面的示例中,即使

@Auditable
中的 A 字母为大写,而
@annotation(auditable)
中的字母 a 为小写,
@Auditable
表达式如何与
@annotation(auditable)
表达式匹配?

我尝试阅读文档,但它只是呈现事实,而没有解释注释表达式匹配的边界以及在什么情况下可能会失败。我期望注释匹配区分大小写,但我认为更深层次的事情正在发生,例如

@Auditable
注释的对象创建,然后该对象以某种方式与方面匹配。

java spring spring-boot aop aspectj
1个回答
0
投票

Spring AOP 或 AspectJ 中的注释按其类型进行匹配。语法为

@annotation(my.package.MyAnnotation)
@annotation(myAnnotationParameter)
与建议参数(如
MyAnnotation myAnnotationParameter
)组合,例如

@Before("@annotation(auditable)")
public void audit(Auditable auditable) {
  System.out.println(auditable.value());
  // ...
}

或者,如果您需要连接点,

@Before("@annotation(auditable)")
public void audit(JoinPoint joinPoint, Auditable auditable) {
  System.out.println(joinPoint + " -> " + auditable.value());
  // ...
}

如果注释参数像这样绑定到建议参数,则建议方法签名中的名称和切入点中的名称应该完全匹配,即区分大小写。

但是你的例子没有任何意义,我怀疑你是否在任何类似的教程中找到了它:

@Before("@annotation(auditable)")
public void audit(Integer auditable) { // ???
  AuditCode code = auditable;          // ???
  // ...
}

这不匹配,因为

Integer
不是注释类型。它甚至无法编译,因为你不能将
Integer
分配给
AuditCode
的任何类型 - 除非
AuditCode
恰好是
Integer
子类。

下次,请不要在 Stack Overflow 上直接发布未经测试的伪代码,而是在本地计算机上实际编译并运行的代码。

© www.soinside.com 2019 - 2024. All rights reserved.