triumph
triumph

Reputation: 41

Use AspectJ to monitor database access methods

I want to use AspectJ to monitor database statements.

When I define the pointcut as

@Pointcut("execution(* java.sql.*Statement.execute*(..))")

it does not work. But when I define the pointcut as

@Pointcut("execution(* *.*(..))")

it can monitor all methods.

How can I define the pointcut to monitor database access methods only?

Upvotes: 2

Views: 945

Answers (1)

kriegaex
kriegaex

Reputation: 67297

What you say is not true, because with the second pointcut you can capture a whole lot of method executions but nothing inside the JDK. If you think about it for a while you understand why: AspectJ instruments byte code, but only the byte code of your own classes or libraries, not the JDK byte code because you do not weave your aspects into the JDK. Thus, you cannot capture any execution() joinpoints inside the JDK (except if you instrument the class files inside rt.jar or so).

Now how do you solve your problem? First you need to understand the fundamental difference between execution() and call() pointcuts: The former is woven into callees, i.e. right into the target methods. The latter is woven into callers, i.e. into all places where the target method is called.

So you want to try

@Pointcut("call(* java.sql.*Statement.execute*(..))")

But there is a caveat: You are fine if your own code, i.e. the one compiled with AspectJ, calls the statements directly. If you are interested in capturing calls made by 3rd party libraries as well, you either need to weave those as well via binary weaving (producing a new library with woven class files replacing the original one) or via load-time weaving (instrumenting the byte code while it is loaded during runtime). Both is possible. But how to do that is beyond the scope of this article, please read the AspectJ documentation for instructions. Last but not least, if JDK code calls those methods internally, you will not be able to capture the calls by any other means than also weaving the JDK (rt.jar or wherever the SQL code resides), as mentioned above.

I know this is a complex answer to a simple question, but you really need to understand AspectJ before you use it, otherwise you might not fully grasp what I was trying to explain. AspectJ is fun to learn and experiment with, take your time and enjoy it. If you just copy and paste code snippets you are but a fool with a (very powerful) tool. :-)

Upvotes: 7

Related Questions