I've created very basic aspectJ project. I have no idea why advice cannot be applied.
annotation
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Conditional {
String value();
}
and aspectJ class:
@Aspect
public class AspectE {
@Around("call(@Conditional * *.*(..)) && @annotation(conditional)" )
public Object condition(ProceedingJoinPoint joinPoint, Conditional conditional) throws Throwable {
System.out.println("entry point says hello!");
return joinPoint.proceed();
}
}
main:
public class Main {
@Conditional("")
public static void main(String[] args) {
System.out.println("main good morning");
}
}
Could you please tell me what I should change to receive both messages?
I think it is because of the call(@Conditional * *.*(..))
which basically weaves the callers , the caller in this specific case is the command line and so there is no weaving happening.
You should probably change it to execution instead, that should work.
@Around("execution(@Conditional * *.*(..)) && @annotation(conditional)" )
You should use AspectJ weaver in order to apply your aspect AspectE
to the Java class Main
. If you're using Maven I would recommend to use aspectj-maven-plugin.
Either your advice must proceed(conditional)
or, if you do not need the object bound to a variable, remove the binding.
Your pointcut matching problem is that there is no place inside your application which calls main
(the Java command line does that), only a place where the method is executed, so you want to change that part of your pointcut to execution(@Conditional * *.*(..))
.
To simplify things, you can remove either part of the pointcut, because both ones will match without redundantly connecting them by &&
.
So the simplest version of the aspect in plain AspectJ syntax is:
public aspect AspectE {
Object around() : @annotation(Conditional) {
System.out.println("entry point says hello!");
return proceed();
}
}