Search code examples
javaannotationsartifact

Custom Java annotation that calls a REST API


I would like to create a Java annotation @Ping that sends a POST request to a REST API that I deployed in a Docker container.

So far, I created this annotation:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Ping {
    String endpoint();
}

As you can see, I would like this annotation to be based on methods. This method will allow me to give a status (available or unavailable) to my other services.

I also would like to store this code as a Maven artifact on my own repo, where I will add a couple more annotations, so that I can use it on my other services.

I have seen a couple tutorials but couldn't figure out how to externalize this behavior, and I couldn't have this working in the first place anyway.

From what I understand, now I need a handler that contains the logic (i.e. that sends a POST request to my API), but I am not sure how to do that. Any chance you can help me get started on this? Is an annotation a good idea to do something like this?

Thanks!


Solution

  • Create a method level annotation and Use AOP to write a logic that will call your rest api

    @Around("execution(@Ping * *(..))")
    public void entr(ProceedingJoinPoint joinPoint) throws Throwable {
     System.out.println("before method");
     joinPoint.proceed();
     System.out.println("after method");
    }