【问题标题】:Can't see annotations via reflection despite RetentionPolicy being RUNTIME尽管 RetentionPolicy 为 RUNTIME,但无法通过反射查看注释
【发布时间】:2018-06-05 16:50:14
【问题描述】:

我正在尝试在 Spring RestController 中查找使用给定注释进行注释的方法。为了查看该 RestController 的方法上存在哪些注释,我执行了以下操作:

Map<String, Object> beans = appContext.getBeansWithAnnotation(RestController.class);
for (Map.Entry<String, Object> entry : beans.entrySet()) {
    Method[] allMethods = entry.getValue().getClass().getDeclaredMethods();
    for(Method method : allMethods) {
        LOG.debug("Method: " + method.getName());
        Annotation[] annotations = method.getDeclaredAnnotations();
        for(Annotation annotation : annotations) {
            LOG.debug("Annotation: " + annotation);
        }
    }
}

问题是我根本看不到任何注释,尽管事实上我知道我至少有一个带有@Retention(RetentionPolicy.RUNTIME) 注释的注释。有任何想法吗? CGLIB 是这里的一个因素吗? (作为控制器,所讨论的方法正在使用 CGBLIB 进行代理)。

【问题讨论】:

  • 请同时添加注解接口代码
  • 有问题的注解是Spring的@PreAuthorize注解。
  • 使用 Spring AnnotationUtils 或至少 AopUtils 获取实际类。您获得了一个代理,并且由于注释不是继承的,您将看不到它们。还有你为什么需要这个?
  • 谢谢@M.Deinum,太好了。该要求涉及记录授权。如果您提交答案,我会将其标记为正确。

标签: java spring spring-mvc reflection cglib


【解决方案1】:

由于@PreAuthorize 注释,您不会获得实际的类,而是该类的代理实例。由于注释不是继承的(通过语言设计),您将看不到它们。

我建议做两件事,首先使用AopProxyUtils.ultimateTargetClass 获取bean 的实际类,然后使用AnnotationUtils 从类中获取注释。

Map<String, Object> beans = appContext.getBeansWithAnnotation(RestController.class);
for (Map.Entry<String, Object> entry : beans.entrySet()) {
    Class clazz = AopProxyUtils. AopProxyUtils.ultimateTargetClass(entry.getValue());
    ReflectionUtils.doWithMethods(clazz, new MethodCallback() {
        public void doWith(Method method) throws IllegalArgumentException, IllegalAccessException {
            Annotation[] annotations = AnnotationUtils.getAnnotations(method);
            for(Annotation annotation : annotations) {
                LOG.debug("Annotation: " + annotation);
            }
        }
    });
}

类似的东西应该可以解决问题,还可以使用 Spring 提供的实用程序类进行一些清理。

【讨论】:

  • 太好了。谢谢马丁。
  • 我是从头顶输入的,所以代码可能存在一些问题。随意提议使用工作代码进行编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-05
  • 1970-01-01
  • 2012-01-20
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多