user3656237
user3656237

Reputation: 207

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!

Upvotes: 0

Views: 1193

Answers (2)

user3656237
user3656237

Reputation: 207

To add to @Urvil Joshi's answer, considering I didn't want to have add a Spring dependency, I created a PingAspect.aj file with this content:

public aspect PingAspect {

    pointcut hasPingAnnotation(Ping ping): @annotation(ping);

    pointcut execute() : execution(* * (..));

    Object around(Ping ping) : execute() && hasPingAnnotation(ping) {
        System.out.println("Before method execution");
        String endpoint = ping.endpoint();
        System.out.println("Endpoint = " + endpoint);
        Object result = proceed(ping);
        System.out.println("After");
        return result;
    }
}

Works perfectly well with the ajc compiler! Hope it can help

Upvotes: 0

Urvil Joshi
Urvil Joshi

Reputation: 38

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");
}

Upvotes: 1

Related Questions