aopaspectjaspect

Getting an error while making the below staticInitialisation advice generic


Since the below given advice works only for a specific class

@Before("staticinitialization(org.mazouz.aop.Main1)")

I tried to make the advice generic such that it can work for any package

@Before("staticinitialization(*.*.*(..))")

Im getting the below error

Syntax error on token "staticinitialization(*.*.*(..))", ")" expected

Solution

  • If you look at the AspectJ documentation (Programming Guide, AJ5 Developer's Notebook) and your own first example, you will notice that statitinitialization takes a pointcut patter representing a type name, not any kind of method or constructor call, which makes sense, as you are trying to intercept static class initialsation, where you only have the class name to work with.

    You also ought to use simpler patterns instead of *.*.*, e.g. * (all classes) or org.acme.my_app..*.

    Last but not least, you need to exclude the aspect itself when using a global pattern that would match the aspect class itself. Otherwise you get errors like:

    Exception in thread "main" java.lang.ExceptionInInitializerError
        at de.scrum_master.app.Application.<clinit>(Application.java:1)
    Caused by: org.aspectj.lang.NoAspectBoundException: de.scrum_master.aspect.MyAspect
        at de.scrum_master.aspect.MyAspect.aspectOf(MyAspect.aj:1)
        at de.scrum_master.aspect.MyAspect.<clinit>(MyAspect.aj:1)
        ... 1 more
    

    Here is an MCVE:

    package de.scrum_master.app;
    
    public class Application {
      public static void main(String[] args) {
        System.out.println("Hello world!");
      }
    }
    
    package de.scrum_master.aspect;
    
    import org.aspectj.lang.JoinPoint;
    import org.aspectj.lang.annotation.Aspect;
    import org.aspectj.lang.annotation.Before;
    
    @Aspect
    public class MyAspect {
      @Before("staticinitialization(*) && !within(MyAspect)")
      public void beforeAdvice(JoinPoint joinPoint) {
        System.out.println(joinPoint);
      }
    }
    

    Console log:

    staticinitialization(de.scrum_master.app.Application.<clinit>)
    Hello world!