在通知前后传递对象? [英] Pass object between before and after advice?
问题描述
是否可以在 before 通知中创建一个对象并将其传递给 after 通知?例如,如果我有方面:
Is it possible to create an object in a before advice and pass it to an after advice? For instance, if I have the aspect:
public aspect LoggingAspect {
pointcut allMethods() : execution(* com.foo.Bar.*(..));
before() : allMethods() {
SomeObject foo = makeSomeObject();
}
after() : allMethods() {
// access foo?
}
}
我不能直接引用 foo
因为它不在范围内(触发编译器错误).是否有一些上下文可用于我可以将 foo
存储在其中的两个建议?
I can't directly reference foo
since it's not in scope (triggers a compiler error). Is there some context available to both advices that I can store foo
inside?
背景:我打算创建一个唯一标识符来引用该方法的这个特定调用,我需要在两个建议中访问它,因为我会将它包含在日志输出中.
Background: I intend to create a unique identifier to refer to this particular invocation of the method and I need access to it in both advices, since I will include it in logging output.
在我的建议类中存储参数不是一种选择(因为我希望它不知道建议).
Storing a parameter within my advised class is not an option (since I want it to be unaware of the advice).
推荐答案
你可以把它存储在一个成员变量中,但是你必须考虑线程安全.相反,我强烈建议使用 around
建议.
You could store it in a member variable, but then you have to think about thread safety. Instead I highly recommend to use an around
advice.
Object around() : allMethods() {
SomeObject foo = makeSomeObject();
Object ret = proceed();
foo.magic();
return ret;
}
这篇关于在通知前后传递对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!