我无法评论 Biju 的答案,所以我正在创建一个新答案:
您询问:
有一个问题:“建议 [...] 尚未应用 [Xlint:adviceDidNotMatch]” - 切入点似乎与 Java 方法不再匹配
嗯,应该怎么搭配?在执行你的静态方法(你自己提到过)时没有this
对象,所以切入点应该是call()
而不是execution()
. 这是我为您创建的完整代码示例以进行演示:
应用类:
package de.scrum_master.aspectj.sample;
import java.util.Random;
public class Dummy {
static Random random = new Random();
static void myMethod_one() throws InterruptedException {
Thread.sleep(random.nextInt(1000));
}
static String myMethod_two(int dummy) throws InterruptedException {
Thread.sleep(random.nextInt(1000));
return "dummy";
}
static int myMethod_three(double foo, String... dummy) throws InterruptedException {
Thread.sleep(random.nextInt(1000));
return -1;
}
public static void main(String[] args) throws InterruptedException {
// We have no "this" here (static method), so advice is not applied
myMethod_two(5);
myMethod_one();
myMethod_three(7.7, "foo", "bar");
// Now let's create an object, so we have "this"
new Dummy().doStuff();
}
void doStuff() throws InterruptedException {
// Here advice is applied because we have "this"
myMethod_one();
myMethod_two(5);
myMethod_one();
myMethod_three(7.7, "foo", "bar");
myMethod_three(3.3, "zot", "baz");
myMethod_two(11);
}
}
时序方面:
package de.scrum_master.aspectj.sample;
aspect TimingAspect {
pointcut calculation(Object thisObject) :
call(* myMethod_*(..)) && this(thisObject);
Object around(Object thisObject) : calculation(thisObject) {
long start = System.nanoTime();
Object result = proceed(thisObject);
long end = System.nanoTime();
System.out.println(String.format(
"%s (this = %s) took %d ns",
thisJoinPointStaticPart.getSignature(),
thisObject,
end - start
));
return result;
}
}