在调用org.apache.commons.logging.Log.warn之前的Aspect

时间:2014-05-05 13:54:39

标签: apache log4j aop aspectj

我想要做的是,有一个方面可以监听对org.apache.commons.logging.Log.warn的调用并在调用之后做一些事情。

这可能吗?

我创建了这样一个方面,但是当我执行LOG.warn时它不会被调用:

@Pointcut("execution(* org.apache.commons.logging.Log.warn.*.*(..))")
public void warn() {}

@Around("warn()")
public void collect(JoinPoint joinPoint) throws Throwable {
  System.out.println("debug - 1"); // I have a breakpoint here that never gets hit
}

测试类:

private static final Log LOG = LogFactory.getLog(TestCollectMessagesAspect.class);

public String testCall(String param) {
    LOG.warn("this is a test");
    return param;
}

由于

1 个答案:

答案 0 :(得分:1)

这是AspectJ初学者的典型陷阱:您试图拦截方法execution(),但为了实现这一点,您需要将您的方面编织到目标代码中,即在这种情况下编译为Commons Logging。为了做到这一点,你必须进行二元编织并创建第三方JAR的编织版本。

虽然这是可能的,但是有一个更简单的解决方案,只要您控制调用代码并且只对您自己的代码创建的警告感兴趣,而不是其他第三方库等。如果是这样,只需从execution()切换到call()切入点即可。这将编织呼叫者而不是被呼叫者。