[英]How to get the associated Parameter with Custom Annotation
@RestController
public class TestController {
@GetMapping("/hello/{userId}")
@Audit(type = AuditType.CREATE)
public String hello(@AuditField @PathVariable long userId) {
return "hello";
}
}
我要掃描的@Audit注釋與@AuditField一起。 @Audit掃描工作正常,但我也想獲取@AuditField參數值。 在我的情況下是userId 。
我為@AfterReturning建議定義了方面。
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顯示為空。
您通過對方法參數進行注釋而以某種方式成為注釋類的instanceof
的假設是錯誤的,而且非常不合邏輯。 相反,您需要做的是掃描方法簽名中的參數注釋,然后在方法簽名的相應位置處返回方法參數,類似於這些答案中的示例代碼,每個示例都顯示出您的問題的稍有不同:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.