简体   繁体   中英

Get annotations of return type in Java

I'm using Spring MVC and am using aspects to advise my controllers. I'm running into one issue: controllers that return a value annotated with the @ResponseBody type. How are you able to find the annotations applied to the return type?

@Around("myPointcut()")
private Object checkAnnotations(ProceedingJoinPoint pjp) throws Throwable {
    Object result = pjp.proceed();
    Method method = ((MethodSignature)pjp.getSignature()).getMethod();
    System.out.println("Checking return type annotations.");
    for(Annotation annotation : method.getReturnType().getAnnotations()){
        System.out.println(annotation.toString());
    }
    System.out.println("Checking annotations on returned object.");
    for(Annotation annotation : result.getClass().getAnnotations()){
        System.out.println(annotation.toString());      
    }
    return result;
}

The method being advised:

@RequestMapping("/Test")
public @ResponseBody String doTest(){
    return "Test";
}

Unfortunately, neither of these methods seem to have the desired effect. I can retrieve annotations on the type of object being returned, but not the ones being added at return time.

The @ResponseBody annotation annotates a method , so i would imagine you would want to get the method annotations.

i'm not a spring expert, but the examples i saw looked like:

@RequestMapping("/Test")
@ResponseBody
public String doTest(){
    return "Test";
}

It is a type annotation. It is available since Java 8. This gives you a head start: http://java.dzone.com/articles/java-8-type-annotations

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM