Saturday, November 20, 2004

AOP Jargon

Aspect Oriented Programming (AOP) introduced a lot of new jargon (as if there wasn't enough already). And the problem with AOP jargon is that it's not very intuitive, and I think this scares away some people. Because, in fact, AOP is not that complicated. I've been exploring Spring AOP, and I'll try to explain some of the AOP jargon used in Spring (most of the concepts are the same in others AOP implementations).
The most common example associated with AOP is logging. Logging is something that we have to do across a lot of classes (if not all). And most of the times the code is the same, across all those classes. Wouldn't be nice if we could just say: "let there be logging in all these classes". Well, we can. That's AOP.

Let's assume we want to log everytime the foo() method is called.


public class AOPTest {

public void foo(){

...interesting stuff...
}
}

The normal solution would be to add something like System.out.println("Entering method foo"); at the start of the foo method (or something a little better than System.out.println). With AOP we can tell that a given piece of code is executed before any call to foo(). That piece of code is called an Advice. There are different kinds of advices for several situations:
  • before advice - executed before the method
  • after advice - executed after the method
  • throws advice - executed if a specific exception is thrown
  • around advice - intercepts the method, and can be used to change arguments or even preventing the method from being called
  • introduction - adds methods to the class, allowing it to implement another java interface
The type of advice already specifies when it should occur, at least in part. We still need to tell what classes and/or methods are intercepted by the Advice. This is done with a Pointcut. A Pointcut simple defines when an Advice (generically speaking, not a specific advice) should occur. For example: you can specify regular expressions to match class and/or method names (you can match only the class name to apply an Advice to all the methods in the class). So, now that you have an Advice and a Pointcut you may join the two in an encapsulating class called Advisor (basically, simplifies configuration).
This should be enough, but Spring implements AOP trough proxies. Every method call is intercepted by a proxy class, before getting to the real method. This is how Advices are executed transparently before or after some method. Fortunately, you don't' have to create proxies manually for every target class (although you can, if additional flexibility is required).

I think this is all the jargon one needs to know to get started on Spring AOP...or any other AOP implementation. I used Spring AOP mainly because I was already exploring Spring Framework, but there are others more powerful that Spring AOP, like AspectJ or AspectWerkz.

0 comentários: