Use aspectj to profile selected methods

I would like to use aspectj to profile the library. My plan was to mark methods that require profiling with annotation:

@Profiled("logicalUnitOfWork")

And then you have an aspect that will fire before and after methods that will use logicalUnitOfWork to highlight profiled content.

So, my pointcut for starters looks like this. Note that there is no argument for annotation; that one of the things i'm not sure how to do is:

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

The methods used will be defined as follows:

 @Profiled("someAction") public void doAction (args...) {} 

In short, how can I get the value of @Profiled annotation in an aspect? I don’t need to limit which profiling is based on value, I just need it to be visible for advice. Also, do I need the annotation hold to be set at runtime for this to work, or can I instead save at class level?

+4
source share
2 answers

I'm not sure if this is the best way to do this, but you can 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()); }
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 need to set @Retention to RUNTIME .

+2
source

I did something similar a while ago to annotate fields with default values. I tried to adapt it to the annotated methods that shoud work find. Of course you should add a bit of error checking and zero testing here, since I left this for brevity.

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

 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 is probably recommended to use the around tip:

 around(): profiled() { String opName = getOperationName(thisJoinPoint); Profiler.startEvent(opName); proceed(); Profiler.endEvent(opName); } 
+1
source

All Articles