AspectJ - Creating a global Logger field using an Inter-Type Declaration

后端 未结 2 1711
滥情空心
滥情空心 2021-01-06 21:58

I\'d like to create an Inter-Type declaration that declares a (static final) Logger instance inside each class.

The constructor should be passed the enclosing class

2条回答
  •  囚心锁ツ
    2021-01-06 22:22

    This answer gives the correct solution, posted below for convenience. Additionally it uses AspectJ annotations which is the preferred notation nowadays.

    The developers recently added the annotation API, I presume with the intention of standardising the markup as many other popular libraries like Spring are also doing.

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

提交回复
热议问题