简体   繁体   中英

How to intercept all methods annotated by @Validatable

I have the annotation @Validatable and I want to intercept all calls to methods with that annotation returning int . For intsance:

@Validatable
public int method(){
   //...
}

How can I write the pointcut to do that? In general, I need to write the following aspect:

public aspect ValidateAspect {
    pointcut publicMethodExecuted(): execution(__HERE_SHOULD_BE_THE_PATTERN__);

    int around() : publicMethodExecuted() {
        //performing some validation and changing return value
    }
}

You can perform what you want once you get the annotations belonging to the int method() method using the following code :

pointcut publicMethodExecuted(): execution(public int <classname>.method());
int around() : publicMethodExecuted() {
  //performing some validation and changing return value
  MethodSignature signature = (MethodSignature) thisJoinPoint.getSignature();
  String methodName = signature.getMethod().getName();
  Annotation[] annotations = thisJoinPoint.getThis().getClass().getDeclaredMethod(methodName).getAnnotations();
  for (Annotation annotation : annotations)
      System.out.println(annotation);
 }

AspectJ supports quite simply PointCut Designators for annotated method. For your use case, it is :

public aspect ValidateAspect {
    pointcut publicMethodExecuted(): @annotation(Validatable);

    int around() : publicMethodExecuted() {
        //performing some validation and changing return value
    }
}

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