使用Aspectj剖析所选方法 [英] Use aspectj to profile selected methods
问题描述
我想用AspectJ来描述一个库.我的计划是用注释标记需要剖析的方法:
I'd like to use aspectj to profile a library. My plan was to mark methods that require profiling with an annotation:
@Profiled("logicalUnitOfWork")
然后有一个方面可以在使用logicalUnitOfWork
突出显示配置文件内容的方法之前和之后触发.
And then have an aspect that would fire before and after methods that would use the logicalUnitOfWork
to highlight the profiled content.
所以,我的切入点看起来像这样.请注意,我这里没有注释的参数.这是我不确定如何做的事情之一:
So, my pointcut to start with looks like this. Note that I don't have the argument for the annotation here; that's one of the things I'm not sure how to do:
pointcut profiled() : execution(@Profiled * *());
before() : profiled () {
// : the profiled logical name is in this variable:
String logicalEventType;
Profiler.startEvent (logicalEventType);
}
after() returning : profiled() {
// : the profiled logical name is in this variable:
String logicalEventType;
Profiler.endEvent (logicalEventType);
}
正在分析的方法将这样定义:
The methods being profiled would be defined like this:
@Profiled("someAction")
public void doAction (args...) {}
简而言之,如何将@Profiled
批注的值添加到方面中?我不需要根据值来限制进行哪个概要分析,我只需要对建议可见即可.另外,是否需要将注释的保留时间设置为运行时才能起作用,还是可以将类级别的保留时间改为?
In short, how can I get the value of the @Profiled
annotation into the aspect? I don't need to restrict which profiling occurs based on the value, I just need it to be visible to the advice. Also, do I need to have the annotation's retention set to runtime for this to work, or can I have class-level retention instead?
推荐答案
我不确定这是否是最好的方法,但是您可以尝试以下方法:
I am not sure if this is the best way to do it, but you could try something like:
pointcut profiledOperation(Profiled p) :
execution(@Profiled * *()) && @annotation(p);
before(Profiled p): profiledOperation(p)
{
System.out.println("Before " + p.value());
}
after(Profiled p): profiledOperation(p)
{
System.out.println("After " + p.value());
}
由于您需要在运行时访问批注值,因此必须将@Retention
设置为RUNTIME
.
Since you need to access the annotation value at runtime you will have to set the @Retention
to RUNTIME
.
这篇关于使用Aspectj剖析所选方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!