我试图在我的bean上获取方法的注释,但注释列表返回空。我就是这样做的。
@PostConstruct
public void findSensitiveAnnotations(){
Map<String,Object> beans = applicationContext.getBeansWithAnnotation(RestController.class);
for (Map.Entry<String, Object> entry : beans.entrySet()){
for (int i=0 ; i<entry.getValue().getClass().getDeclaredMethods().length ; i++){
System.out.println(entry.getValue().getClass().getDeclaredMethods()[i]);
for (Annotation a : entry.getValue().getClass().getDeclaredMethods()[i].getAnnotations()){
System.out.println(a.toString());
}
}
}
}
第一个System.out.println()
打印的内容如下:
public final org.springframework.http.ResponseEntity com.company.product.web.rest.AccountResource$$EnhancerBySpringCGLIB$$dff83dd3.sendResetEmail(java.lang.String,javax.servlet.http.HttpServletRequest)
但是第二个System.out.println()
从未被调用,注释列表长度== 0。
以下是与sendResetEmail(@RequestParam String email, HttpServletRequest request)
@RequestMapping(value = "/reset/byEmail",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Sensitive
public ResponseEntity<String> sendResetEmail(@RequestParam String email, HttpServletRequest request) {...}
我的注释:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Sensitive { }
答案 0 :(得分:1)
getBeansWithAnnotation似乎不会返回真正的类名。
尝试做类似的事情:
Map<String,Object> beans = applicationContext.getBeansWithAnnotation(Service.class);
for (Map.Entry<String, Object> entry : beans.entrySet()){
Class<?> clazz = entry.getValue().getClass();
//System.out.println(clazz.getName());
String[] split = clazz.getName().split("\\$");
String realClassName = split[0];
//System.out.println(realClassName);
Class<?> myClass = getClass().getClassLoader().loadClass(realClassName);
Method[] methods = myClass.getDeclaredMethods();
for(Method method: methods) {
for (Annotation a : method.getAnnotations()){
System.out.println(a.toString());
}
}
}
答案 1 :(得分:0)
我认为您需要拨打getDeclaredAnnotations()
而不是getAnnotations()