java - 尽管 RetentionPolicy 为 RUNTIME,但无法通过反射查看注释

标签 java spring spring-mvc reflection cglib

我试图在 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 是这里的一个因素吗? (作为 Controller ,有问题的方法使用 CGBLIB 进行代理)。

最佳答案

由于 @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 提供的实用程序类进行一些清理。

关于java - 尽管 RetentionPolicy 为 RUNTIME,但无法通过反射查看注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50695155/

相关文章:

java - session 事件在 Spring session 中不起作用

java - 带有 spring 数据的 mongodb 查询键值

java - 在Python中修改条件表达式中的变量

JAVA 计算 3^n - 3*2^n + 3 的最优方法。

java - 使用spring mongo查询oplog时间戳

java - 在没有 HTTP 请求/servlet 的情况下使用 @RequestMapping 功能(URL 到 Java 方法映射)

rest - 带有错误的不同内容类型编码的Spring Boot(MVC)响应

Java - 如何通过HTTP请求而不是文件读取xls格式数据

java - _XReply() 使用 _XIOError() 终止应用程序

java - 使用数组列表对程序进行故障排除,java