I'd like to use aspectj to profile a library. My plan was to mark methods that require profiling with an annotation:
@Profiled("logicalUnitOfWork")
And then have an aspect that would fire before and after methods that would use the logicalUnitOfWork
to highlight the profiled content.
So, my pointcut to start with looks like this. Note that I don't have the argument for the annotation here; that's one of the things I'm not sure how to do:
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 being profiled would be defined like this:
@Profiled("someAction")
public void doAction (args...) {}
In short, how can I get the value of the @Profiled
annotation into the aspect? I don't need to restrict which profiling occurs based on the value, I just need it to be visible to the advice. Also, do I need to have the annotation's retention set to runtime for this to work, or can I have class-level retention instead?
I am not sure if this is the best way to do it, but you could try something like:
Since you need to access the annotation value at runtime you will have to set the
@Retention
toRUNTIME
.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.
To avoid too much reflection, it's probably a good idea to use
around
advice instead: