首页 > 解决方案 > 自定义注释没有得到参数的值

问题描述

在 Spring 中编写它并尝试使用自定义注释,该注释从方法的参数中获取值并对其执行一些逻辑。但它不起作用。它最终打印出我传入的字符串值,而不是变量的值。

示例变量名为 name,其值为“Dan”。当我传入参数时,它最终会打印出“name”而不是“Dan”。如果我在 Spring 中对 Cacheable 注释做同样的事情,它工作得很好。使用 Intellij 甚至基于 ide 的突出显示,当我将参数传递给 @Cacheable 时,它​​似乎可以识别该参数,但对于我的自定义注释却不是这样。请指教我做错了什么。

我的自定义注释

@Target(ElementType.METHOD)

@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnot {
    String key();
}

实现注解。当我期待“Dan”时,这错误地打印出“#key”

@CustomAnnot(key = "#key")
public Object getObj(String key) {
    return null;
}

为可缓存的有效的传递相同表达式的示例。

@Cacheable(key = "#key")
public Object getAnotherObj(String key) {
    return null;
}

相信这段代码不会引起任何问题。只是添加它以防万一。使用注释重定向到发生打印的 Aspect 类,我在其中验证它是否打印错误。

@Around("@annotation(CustomAnnot)")
public Object get(ProceedingJoinPoint pjp, CustomAnnot customAnnot) throws Throwable {
    String key = customAnnot.key();
    System.out.println(key);
}

标签: javaannotationsspring-aop

解决方案


如果你想要的只是基于你的 key 的参数值,你可以做这样的事情。异常处理被遗漏了。

@Around("@annotation(customAnnot)")
  public Object get(ProceedingJoinPoint pjp, CustomAnnot customAnnot) throws Throwable {
    MethodSignature signature = (MethodSignature) pjp.getStaticPart().getSignature();
    List<String> paramsList = Arrays.asList(signature.getParameterNames());
    List<Object> argsList = Arrays.asList(pjp.getArgs());
    String key = customAnnot.key();
    key = key.substring(1);

    logger.info("[{}]", argsList.get(paramsList.indexOf(key)));
    return key;
  }

打电话

test.getObj("Dan");

版画:[丹]


推荐阅读