如何使用自定义注释获取关联的参数

问题描述 投票:0回答:1
@RestController
public class TestController {

    @GetMapping("/hello/{userId}")
    @Audit(type = AuditType.CREATE)
    public String hello(@AuditField @PathVariable long userId) {
        return "hello";
    }

}

我想和@AuditField一起扫描@Audit Annotation。 @Audit扫描工作正常,但我也希望获得@AuditField参数值。在我的情况下userId。

我为@AfterReturning建议定义了Aspect。

import java.lang.annotation.Annotation;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Aspect
@Component
public class AuditAspect {

  @AfterReturning(pointcut = "@annotation(audit)", returning = "result")
  public void audit(JoinPoint jp, Object result, Audit audit) throws Exception {

   List<Object> auditFields = getAuditData(jp.getArgs());
   System.out.println(auditFields);
  }

  private List<Object> getAuditData(Object[] args) {
    return Arrays.stream(args)
        .filter(arg -> arg instanceof AuditField)
        .collect(Collectors.toList());
  }
}

但是在访问hello / 1时,auditFields显示为空。

java annotations spring-aop
1个回答
0
投票

你的假设通过注释一个方法参数,它以某种方式成为一个instanceof注释类是错误的,非常不合逻辑。您需要做的是扫描参数注释的方法签名,然后在方法签名的相应位置返回方法参数,类似于我在这些答案中的示例代码,每个都显示您的问题的略有不同的变体:

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