Spring AOP: how to get the annotations of the adviced method

前端 未结 5 1012
我在风中等你
我在风中等你 2020-12-14 21:28

I\'d like to implement declarative security with Spring/AOP and annotations. As you see in the next code sample I have the Restricted Annotations with the paramter \"allowed

5条回答
  •  独厮守ぢ
    2020-12-14 21:38

    Even after changing the retention policy like Bozho mentioned this call to get annotation returns null:

    targetMethod.getAnnotation(Restricted.class);
    

    What I found is you have to bind the annotation. Given the interface is declared like this:

     @Retention(RetentionPolicy.RUNTIME)
     public @interface Restricted {
         String[] allowedRoles();
      }
    

    The advice would need to be declared like this:

           @Before("@annotation( restrictedAnnotation )")
           public Object processRequest(final ProceedingJoinPoint pjp, Restricted restrictedAnnotation) throws Throwable {
                      String[] roles = restrictedAnnotation.allowedRoles();
                      System.out.println("Allowed:" +  roles);
           }
    

    What this does is bind the annotation to the parameter in the method signature, restrictedAnnotation. The part I am not sure about is how it gets the annotation type, it seems to be based on the parameter. And once you have the annotation you can get the values.

提交回复
热议问题