我想要进行 REST API 调用,该调用返回一个 boolean 值作为自定义注释的一部分。
示例代码:
**@CustomAnnotation
public String myMethod(){
// my implementation
}**
只有当 REST 调用的 boolean 值为 true 时,方法“myMethod 才必须被触发并执行,否则会抛出类似于 @NotNull 的异常。 我想知道这是否可能,如果可以,请有人帮助我。
最佳答案
您可以创建一个简单的自定义注释,而不必担心调用休息的代码。 用于执行其余调用代码 ->
了解如何应用面向方面的编程。
基本上使用 aop(面向 apsect 的编程),您可以编写这样的代码,对于使用自定义注释进行注释的任何方法,您希望在调用您的方法之前执行一些代码。
在 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();
}
}
关于java - 如何在自定义注释中进行 Rest API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62318253/