我试图在我的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 { }

最佳答案

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());
            }
        }
    }

07-24 19:14
查看更多