【问题标题】:Use aspectj to profile selected methods使用 aspectj 分析选定的方法
【发布时间】:2009-02-11 18:01:15
【问题描述】:

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

【问题讨论】:

    标签: java profiling aop aspectj


    【解决方案1】:

    我不确定这是否是最好的方法,但您可以尝试以下方法:

    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

    【讨论】:

    • 这当然有帮助,尽管理想情况下我希望注释只保留在类文件中。 AspectJ weaving 发生在那个时候,所以我希望它能够获得价值。
    • 我稍微简化了原始示例,但我认为您仍然需要将保留设置为运行时。如果您只想通过注解进行匹配,类级别就足够了,但您还需要在运行时访问它以注册分析事件。
    【解决方案2】:

    不久前我做了类似的事情来用“默认值”注释字段。我试图将其调整为应该可以找到的带注释的方法。当然,您应该在此处添加一些错误检查和空值测试,因为为简洁起见,我将其省略了。

    可以使用连接点的静态部分获取注解的值。

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

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-12
      • 1970-01-01
      • 2012-01-02
      相关资源
      最近更新 更多