aspectj: why advice cannot be applied?

2019-07-23 05:23发布

问题:

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?

回答1:

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



回答2:

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.



回答3:

  1. Either your advice must proceed(conditional) or, if you do not need the object bound to a variable, remove the binding.

  2. 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 * *.*(..)).

  3. 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();
    }
}


标签: java aspectj