2

I have problem with AspectJ. I added arguments to annotation before which Aspect will be woven and as a result it doesn't work.

Annotation interface:

@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Logged {
   Event event();
   System system();
}

My Aspect:

@Aspect
@Component
public class Aspect {
    @Pointcut("@annotation(Logged) && args(event, system)")
    public void invoke(Event event, System system) { }

    @Around("invoke(event, system)")
    public void aspectMethod (ProceedingJoinPoint, Event event, System system) {
        System.out.println(event + " " + system);
    }
}

Event and System are Enums.

and added annotation before some method like that:

@Logged(event = Event.USER_LOGGED, system = System.WIN)
someTestingMethod();

It works only when I leave Aspect as:

@Aspect
@Component
public class Aspect {
    @Pointcut("@annotation(Logged)")
    public void invoke() { }

    @Around("invoke()")
    public void aspectMethod (ProceedingJoinPoint) {
        System.out.println("Hey");
    }
}

I don't know how to pass arguments into Aspect with annotation.

Hunteerq
  • 250
  • 1
  • 4
  • 15

1 Answers1

2

The basic solution is to bind the annotation:

@Aspect
class MyAspect {
    @Pointcut("execution(* *(..)) && @annotation(l)")
    public void invoke(Logged l) {}

    @Around("invoke(l)")
    public void aspectMethod (ProceedingJoinPoint pjp, Logged l) {
        java.lang.System.out.println(l.event()+" "+l.system());
    }
}

I've used the execution() pointcut to select only methods (so we want annotated methods) otherwise it will bind other users of the annotation (on fields/types/etc). As someone pointed out, args is for binding method parameters, rather than annotations.

Andy Clement
  • 2,510
  • 16
  • 11