我试图在 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/