I want to write an annotation in Java, which executes something before and after execution of the annotated method, similar to what can be done in Spring with aspects.
I've already tried a Spring aspect, but it only works for Beans (as this guy here mentioned) and I want to stay independent from the Spring framework.
A simple class that writes a String to the console:
public class Main {
public static void main(String[] args) {
say("How are you?");
}
@Hello
private static void say(String s) {
System.out.println(s);
}
}
The associated annotation:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Hello {}
And I need something like (deduced from the Spring aspect)
public Object process(ProceedingJoinPoint proceedingJoinPoint) {
System.out.println("Hello");
Object proceed = null;
try {
proceed = proceedingJoinPoint.proceed();
} catch (Throwable throwable) {
throwable.printStackTrace();
}
System.out.println("world!");
return proceed;
}
I want the following output:
Hello
How are you?
world!
Edit:
I created the following Aspect (without annotations), but it does not work
@lombok.extern.java.Log
public aspect Log {
pointcut methodExecuted():execution(* **(..));
void around(): methodExecuted() {
log.info("Hello");
proceed();
log.info("world!");
}
}
Where is my mistake?