Java 提取通知的相同代码

Java 提取通知的相同代码,java,aspectj,Java,Aspectj,我有两个建议: public aspect LogAspect { before() : execution(@Log * *(..)) { System.out.println(thisJoinPoint.getClass()); Logger logger = Logger.getLogger(thisJoinPoint.getClass()); String className = thisJoinPoint.getClass().g

我有两个建议:

public aspect LogAspect {
    before() : execution(@Log * *(..)) {
        System.out.println(thisJoinPoint.getClass());
        Logger logger = Logger.getLogger(thisJoinPoint.getClass());
        String className = thisJoinPoint.getClass().getSimpleName();
        System.out.println(thisJoinPoint.getSignature().getName());
        String methodName = thisJoinPoint.getSignature().getName();
        String startInfoMessage = String.format("%s.%s: execution started", className, methodName);
        logger.info(startInfoMessage);
    }

    after() : execution(@Log * *(..)) {
        System.out.println(thisJoinPoint.getClass());
        Logger logger = Logger.getLogger(thisJoinPoint.getClass());
        String className = thisJoinPoint.getClass().getSimpleName();
        System.out.println(thisJoinPoint.getSignature().getName());
        String methodName = thisJoinPoint.getSignature().getName();
        String endInfoMessage = String.format("%s.%s: execution's finished", className, methodName);
        logger.info(startInfoMessage);
    }
}
有很多代码重复。我试图将同一个身体提取到一个分离的方法中,如下所示

 private String getInfoMessage(String pattern){
        System.out.println(thisJoinPoint.getClass());
        Logger logger = Logger.getLogger(thisJoinPoint.getClass());
        String className = thisJoinPoint.getClass().getSimpleName();
        System.out.println(thisJoinPoint.getSignature().getName());
        String methodName = thisJoinPoint.getSignature().getName();
        String infoMessage = String.format(pattern, className, methodName);
        return infoMessage;
    }

但它不起作用,因为编译器不知道通知之外的
thisJoinPoint
。这些问题的解决方案是什么?

尝试将此连接点作为方法参数传递。如果这不起作用,我认为其他任何东西都不会起作用。从文档中:>thisJoinPoint变量只能在通知的上下文中使用,>就像这只能在非静态方法>和变量初始值设定项的上下文中使用一样@劳伦蒂尔。听起来很合理,谢谢。@LaurentiuL。顺便说一句,你自己是如何避免这种重复的呢?我的日志记录方面没有那么冗长,所以没有必要让它变得更加枯燥。我在我的日志记录点周围使用了一个方法param来传递这个joinpoint。如果这不起作用,我认为其他任何东西都不会起作用。从文档中:>thisJoinPoint变量只能在通知的上下文中使用,>就像这只能在非静态方法>和变量初始值设定项的上下文中使用一样@劳伦蒂尔。听起来很合理,谢谢。@LaurentiuL。顺便说一句,你自己是如何避免这种重复的呢?我的日志记录方面没有那么冗长,所以没有必要让它变得更加枯燥。我在我的日志切入点周围使用