views:

120

answers:

1

I have used AOP within spring with no real problems, mainly for transaction management, for which it works a charm.

My question is this... the only examples I've seen for AOP so far is to pointcut a class that you have created yourself. Is it possible to pointcut a class within a third party library, for example a database connection class. The context is that I wish to create some logs and gather information when an oracle data source executes a call to the database, which is unfortunately contained within a stack of oracle class files. How would you pointcut this class/method when the SQL is executed?

+2  A: 

I think this will work:

  1. Let Spring be responsible for initializing your DataSource
  2. Apply an aspect against the getConnection() method on your DataSource
  3. In your advice, wrap the returned Connection in a new class ("LoggingConnection") which implements Connection and delegates all methods to the "real" wrapped Connection (I believe this is the Decorator pattern)
  4. Add whatever logging code you need to the "LoggingConnection" class

Bear in mind that this approach creates a proxy of the original DataSource and delegates to it for each method call. In the context of a database operation this shouldn't create a lot of additional overhead. You will want to be extremely careful what your code is doing, lest it throw exceptions and prevent Connections from behaving appropriately. Perhaps use try/catch/finally and put the call that delegates to the "real" Connection in your finally block.

Another totally different approach would be to use AspectJ and do load-time weaving. That way you can decorate the class with new functionality as soon as the ClassLoader loads it.

cliff.meyers