考虑以下基本的Foo,Bar和Main类:
package foo;
public class Foo {
public String randomHello(String name) {
byte[] random = Bar.generateRandom();
return random.length + " random " + name + " bytes";
}
}
public class Bar {
public static byte[] generateRandom(){
byte[] b = new byte[20];
new Random().nextBytes(b);
return b;
}
}
public class Main {
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.randomHello("AspectJ"));
}
}
运行Main打印“20个随机AspectJ字节”。我想从Foo.randomHello调用时替换Bar.generateRandom的实现。这是通过以下方面实现的:
public aspect FooBarAspect {
pointcut p_randomHello(String name) :
execution(public String foo.Foo.randomHello(String)) && args(name);
pointcut p_generateRandom() :
call(public byte[] foo.Bar.generateRandom());
Object around(String name) :
cflow(p_randomHello(name)) && p_generateRandom() {
byte[] b = new byte[name.length()];
new Random().nextBytes(b);
return b;
}
}
这有效,Main现在打印“7个随机AspectJ字节”。
如何使用注释表达相同的方面?这是我的尝试:
@Aspect
public class FooBarAnnotatedAspect {
@Pointcut("execution(public String foo.Foo.randomHello(String)) && args(name)")
public void p_randomHello(String name){};
@Pointcut("call(public byte[] foo.Bar.generateRandom())")
public void p_generateRandom(){};
@Around("cflow(foo.FooBarAnnotatedAspect.p_randomHello(String)) && " +
"foo.FooBarAnnotatedAspect.p_generateRandom() && args(name)")
public Object a_foobar(ProceedingJoinPoint joinPoint, String name) throws Throwable {
byte[] b = new byte[10];
new Random().nextBytes(b);
return b;
}
}
这不起作用,我收到以下编译器警告:
advice defined in foo.FooBarAnnotatedAspect has not been applied [Xlint:adviceDidNotMatch]
我已经验证了p_randomHello和p_generateRandom切入点是独立工作的,而不是如此处所示的组合。
答案 0 :(得分:1)
在将其切换为注释样式时,您似乎已经稍微改变了切入点,没有必要这样做(即在p_randomHello()
和@Around
切入点引用中复制args()。这适用于您的设置:@Around("cflow(p_randomHello(name)) && p_generateRandom() "