尽管 RetentionPolicy 是 RUNTIME,但无法通过反射看到注释
Can't see annotations via reflection despite RetentionPolicy being RUNTIME
我正在尝试在 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 代理的)。
由于 @PreAuthorize
注释,您得到的不是实际的 class,而是 class 的代理实例。由于注释不是继承的(通过语言设计),您将看不到它们。
我建议做两件事,首先使用 AopProxyUtils.ultimateTargetClass
获取 bean 的实际 class,然后使用 AnnotationUtils
从 [=20] 获取注释=].
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 提供的实用程序 classes 进行一些清理。
我正在尝试在 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 代理的)。
由于 @PreAuthorize
注释,您得到的不是实际的 class,而是 class 的代理实例。由于注释不是继承的(通过语言设计),您将看不到它们。
我建议做两件事,首先使用 AopProxyUtils.ultimateTargetClass
获取 bean 的实际 class,然后使用 AnnotationUtils
从 [=20] 获取注释=].
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 提供的实用程序 classes 进行一些清理。