java - 如何在自定义注释中进行 Rest API 调用?

标签 java rest annotations

我想要进行 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/

相关文章:

java - 将 JSON 列表转换为 POJO

java - java 中每秒生成 X 个线程

java - REST 异常需要构造函数

html - REST 如何在放入资源时处理查询参数?

rest - 如何通过REST API查找JIRA问题的状态?

java - Pluggable Annotation Processor API 可以检索源代码注释吗?

java - EntityManager 始终为 null 并且未正确注入(inject)

java - 更改方法findByOneCss,他收到了不止一种含义和所有

java - 通过 Maven Tomcat 插件运行时,Hibernate 不解析映射文件

java - org.codehaus.jackson.map.exc.UnrecognizedPropertyException : Unrecognized field "id" (Class Criteria), 未标记为可忽略