Search code examples
javaaspectjaspectsstatic-initialization

@AspectJ syntax for "after() : staticinitialization(*)"


I'm trying to implement a tracing aspect using the pertypewithin instantiation model. In this way, I'll be able to use one logger per class per type.

From some examples arround the we I can find this code to init the logger:

public abstract aspect TraceAspect pertypewithin(com.something.*) {
    abstract pointcut traced();
    after() : staticinitialization(*) {
        logger = Logger.getLogger(getWithinTypeName());
    }
    before() : traced() {
        logger.log(...);
    }
    //....
}

unfortunately, I'm not able to fully translate this to the @AspectJ syntax (it's a project requirement outside my control), especially the part in with I need to setup the logger, executing that code only once.

Is this possible?

Thanks,


Solution

  • @Aspect("pertypewithin(com.something.*))")
    public abstract class TraceAspect {
    
    Logger logger;
    
    @Pointcut
    public abstract void traced();
    
    @Pointcut("staticinitialization(*)")
    public void staticInit() {
    }
    
    @After(value = "staticInit()")
    public void initLogger(JoinPoint.StaticPart jps) {
        logger = Logger.getLogger(jps.getSignature().getDeclaringTypeName());
    }
    
    @Before(value = "traced()")
    public void traceThatOne(JoinPoint.StaticPart jps) {
        logger.log(jps.getSignature().getName());
    }
    }