Spring AOP 计算一个特定方法被另一个方法调用的次数
我有一个带有方法 rangeQuery()
的接口,我试图使用 Spring AOP 跨所有子类型进行分析。特别是,对于任何对 rangeQuery()
的调用,我想知道它在其主体的字段上调用另一个方法 distance()
次数。
我知道我可以编写一个方法来计算所有对距离的调用,如下所示:
@Before("execution(* *.distance(..))")
public void count(JoinPoint joinPoint) {
count++
}
但是,这不会捕获哪个 rangeQuery()
调用调用了它。
有什么想法吗?
I have an Interface with the method rangeQuery()
which I am trying to profile across all subtypes, using Spring AOP. In particular, for any call to rangeQuery()
I'd like to know how many times it calls another method distance()
on a field from its body.
I know that I could write a method that counts all calls to distance as follows:
@Before("execution(* *.distance(..))")
public void count(JoinPoint joinPoint) {
count++
}
However, that would not capture which rangeQuery()
call called it.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
作为最后的手段,在上面的
@Before
建议中,您可以使用Thread.currentThread.getStackTrace()
并查看调用者是否是rangeQuery.
但是,您应该在堆栈跟踪中找到一些固定的“模式”来查找,而不仅仅是检查第 N 个位置来查看它是否是您正在寻找的方法。例如,您知道当时应该以某种给定顺序位于堆栈上的一系列方法,但允许出现任何其他中间堆栈元素。否则,代码中的任何更改都会使建议停止工作。
As a last resort, in the
@Before
advice above, you can make use ofThread.currentThread.getStackTrace()
and see if the caller israngeQuery
.However, you should find some fixed "pattern" to look for in the stack trace and not just check the Nth position to see if it's the method you're looking for. For example, a sequence of methods that you know should be on the stack at that time in some given order but allowing any other intermediate stack elements to occur. Otherwise, any change in your code would make the advice stop working.
您可能必须使用
@Around
,而不是使用@Before
,它允许您使用ProceedingJoinPoint
来获取源位置。在你的情况下,听起来你可能需要
call
而不是execution
,但Spring AOP似乎不支持call
:-Instead of using
@Before
, you probably have to use@Around
that allows you to useProceedingJoinPoint
to get the source location.In you case, it sounds like you might need
call
instead ofexecution
but it seems likecall
is not supported in Spring AOP:-