我想使用 aspectj 来分析图书馆。我的计划是用注释标记需要分析的方法:
@Profiled("logicalUnitOfWork")
然后有一个方面会在使用 logicalUnitOfWork
突出显示分析内容的方法之前和之后触发。
所以,我的切入点看起来像这样。请注意,我这里没有注释的参数;这是我不确定该怎么做的事情之一:
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);
}
被剖析的方法定义如下:
@Profiled("someAction")
public void doAction (args...) {}
简而言之,如何将@Profiled
注解的值获取到切面中?我不需要根据值限制发生哪些分析,我只需要它对建议可见。此外,我是否需要将注释的保留设置为运行时才能使其正常工作,或者我是否可以改为使用类级别的保留?
最佳答案
我不确定这是否是最好的方法,但您可以尝试类似的方法:
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
。
关于java - 使用 aspectj 分析选定的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/538010/