访问 ASPECT 中的方法中的业务方法的局部变量
我想从业务类中的方法、方面类中的方法访问局部变量。例如,
class BusinessClass {
public void simpleTest() {
...
String localString = new String( "test" );
...
}
}
MyAspect {
log() {
// I WANT TO ACCESS THE VALUE OF LOCALSTRING HERE
}
}
我想在 MyAspect 的 log 方法中访问 localString 的值。请告诉我是否有任何方法可以使用 Spring / AspectJ 来完成此任务。另外,有没有一种方法可以在不改变 simpleTest 方法签名的情况下完成?
提前非常感谢!
I want to access a local variable from a method in a business class, in a method which is in an aspect class. For instance
class BusinessClass {
public void simpleTest() {
...
String localString = new String( "test" );
...
}
}
MyAspect {
log() {
// I WANT TO ACCESS THE VALUE OF LOCALSTRING HERE
}
}
I want to access localString's value in log method of MyAspect. Please let me know if there is any way to accomplish this using Spring / AspectJ. Also, is there is a way to accomplish without changing simpleTest method signature?
Thanks much in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不幸的是,局部变量不通过连接点公开。这意味着您无法编写切入点来匹配它们。所以,答案是否定的,你不能直接这样做。
但是,如果您要重构代码以便在方法内部创建局部变量,那么您就可以访问它。
从概念上讲,这种重构可能更适合您的代码。您可以通过将分配封装在命名良好的方法中来明确分配的用途,而不是简单地分配新的局部变量。
例如,这样:
变成这样:
使用这个方法:
那么你可以这样编写一个切入点来捕获局部变量:
Unfortunately, local variables are not exposed via joinpoints. This means that you cannot write a pointcut to match them. So, the answer is no, you cannot do this directly.
However, if you were to refactor your code so that the local variable were created inside of a method, then you could access it.
Conceptually, this kind of refactoring might be better for you code. Rather than simply allocate a new local variable, you can be explicit about what the allocation is doing by encapsulating it in a well-named method.
For example, this:
becomes this:
With this method:
Then you can write a pointcut to capture the local variable this way:
据我了解,方面旨在适用于许多方法(由切入点定义)。因此,他们看不到该方法的内部结构:只看到该方法的参数及其结果。这意味着您无法直接完成您想要的操作,但您可以尝试将您的方法重构为两部分,一个将
localString
作为参数,另一个将localString
作为参数它对其应用默认值。这将为您提供一个方便连接的连接点。 (AspectJ 参考列出了连接点,以及对局部变量不是其中之一。)如果您将“内部”方法设置为私有或包私有,您甚至不会更改该方法的通常理解的签名(因为外部代码将无法依赖于介绍的方法)。As I understand them, aspects are intended to be applicable to many methods (as defined by the pointcut). As such, they don't see the internals of the method: just the arguments to the method and the result from it. This means that what you want can't be done directly, but you could try refactoring your method into two pieces, one that takes the
localString
as an argument, and the other which applies a default value to it. That will then give you a nice convenient joint point to attach to. (The AspectJ reference lists join points, and references to local variables aren't one of them.) If you make the “inner” method private or package-private, you won't even change the generally-understood signature of the method (since external code won't be able to depend on the introduced method).