4

我想使用 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注释的值放入方面?我不需要根据值限制发生的分析,我只需要它对建议可见。另外,我是否需要将注释的保留设置为运行时才能正常工作,还是可以改为使用类级别的保留?

4

2 回答 2

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());
   }

由于您需要在运行时访问注释值,因此您必须@RetentionRUNTIME.

于 2009-02-15T01:18:49.407 回答
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);
}
于 2009-04-07T14:41:05.150 回答