我想使用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
注释的值纳入方面?我不需要根据值限制哪个分析发生,我只需要它对建议可见。此外,我是否需要将注释的保留设置为运行时才能使其正常工作,或者我是否可以使用类级保留?
答案 0 :(得分:2)
我不确定这是否是最佳方式,但您可以尝试以下方式:
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
。
答案 1 :(得分:1)
我做了类似的事情,回到使用“默认值”注释字段。我已经尝试将它改编为带注释的方法,这些方法可以找到工作。当然,你应该在这里添加一些错误检查和空值测试,因为为了简洁起见,我已经把它留了出来。
您可以使用连接点的静态部分获取注释的值。
private String getOperationName(final JoinPoint joinPoint) {
MethodSignature methodSig = (MethodSignature) joinPoint
.getStaticPart()
.getSignature();
Method method = methodSig.getMethod();
Profiled annotation = method.getAnnotation(Profiled.class);
return annotation.value();
}
为了避免过多的反思,改为使用around
建议可能是个好主意:
around(): profiled() {
String opName = getOperationName(thisJoinPoint);
Profiler.startEvent(opName);
proceed();
Profiler.endEvent(opName);
}