0

I want to make a REST API call which return a boolean value as a part of the custom annotation.

Sample Code :

**@CustomAnnotation
public String myMethod(){
 // my implementation
}**

Only if the boolean value from the REST call is true, the method "myMethod must get triggered and implementation should happen else throw an exception similar to @NotNull . I was wondering if this is possible, if yes someone please help me out.

1 Answers1

0

you can create a simple custom annotation without worrying about code to call rest. For executing rest call code ->

Read about how to apply aspect oriented programming.

Basically using aop (apsect oriented programming), you can write a code such that for any method which is annotated with your custom annotation, you wish to execute some piece of code before calling your method.

To do this in spring

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@interface CustomAnnotation {
    String value() default "";
}

@Pointcut(value = "@annotation(CustomAnnotation)")  // full path to CustomAnnotation class
public void abc() {
}

@Around("abc()")
public Object executeSomePieceOfCode(ProceedingJoinPoint joinPoint) throws Throwable {

        System.out.println("this executes before calling method");

        // YOUR CODE TO CALL REST API
        boolean responseFromRestCall = true;  // this flag is set based on response from rest call

        if(responseFromRestCall) {
            // this excutes your method
            Object obj = joinPoint.proceed();
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();

            CustomAnnotation myAnnotation = method.getAnnotation(CustomAnnotation.class);
            String value = myAnnotation.value();
            System.out.println("value : + " + value);
            return obj;
        } else {
            // currently throwing RuntimeException. You can throw any other custom exception.
            throw new RuntimeException();
        }

}
Sahil Garg
  • 167
  • 6
  • Thanks for your help. This is my customAnnotation code : *** @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Custom { AnnotationValue value(); } *** where "AnnotationValue" is an enum defined for my implementation. Now how can I obtain the parameter passed in the value() variable into my REST call code of AOP – Billa123 Jun 12 '20 at 11:03
  • While this answer is correct , a better way to obtain the annotation details can be found in my [answer](https://stackoverflow.com/a/62299322/4214241) to another question. @SahilGarg you may modify the answer to avoid the reflection – R.G Jun 12 '20 at 15:11