java - 自定义注释没有得到参数的值
问题描述
在 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);
}
解决方案
如果你想要的只是基于你的 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");
版画:[丹]
推荐阅读
- javascript - Service Worker 有时缓存不会更新。我必须努力刷新
- javascript - 将 JSON 内容放入 HTML 表中,仅索引工作
- python - 在 Windows 中删除 Temp 文件夹,TypeError:join() 参数必须是 str 或 bytes,而不是 'list'
- python - TypeError: can't pickle _thread._local objects 当试图适应 KerasRegressor
- flutter - "return" 和有什么不一样
”和“产量* “飘飘然? - jsp - 我只是想在jsp和servlet中问一些问题
- java - 基本类型的显式 XML 序列化
- python - 基于准确性优化超参数的正确方法
- swift - iOS 15 通讯通知图片未显示
- python - PyAudio 阻塞流中只有白噪声..?