Use aspectj to profile selected methods

六眼飞鱼酱① 提交于 2019-12-05 16:57:18

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

Since you need to access the annotation value at runtime you will have to set the @Retention to RUNTIME.

I did something similar a while back to annotate fields with "default values". I've tried to adapt it to annotated methods, which shoud work find. You, of course, should add a bit of error checking and null-testing here since I've left that out for brevity's sake.

You can get the value of the annotation using the join point's static part.

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

To avoid too much reflection, it's probably a good idea to use around advice instead:

around(): profiled() {
   String opName = getOperationName(thisJoinPoint);
   Profiler.startEvent(opName);
   proceed();
   Profiler.endEvent(opName);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!