Understanding Spring AOP

aces. picture aces. · Apr 8, 2011 · Viewed 8.7k times · Source

I am working with Spring 3.0 framework and still a novice. Can anyone explain me in layman terms what is AOP programming? (a short example will definitely help)

How does Spring incorporate/enhance/support it?

Answer

MeBigFatGuy picture MeBigFatGuy · Apr 8, 2011

AOP is a way to modify existing classes in a code base to embellish them or change their behavior based on rules defined separately. This modification can be done before the classes are put into a jar/war, or can happen dynamically while the code is being loaded.

The idea is, rather than finding all the points of code that you want to modify in the source code and hand modifying them, you define rules for how to find points of interest in the code base, and what embellishments you would like to do to them. These rules are called aspects (the A of AOP).

The prototypical example is you want to get some timing information on various methods in your code base. You could go find all the methods of interest and at the top put a call to

long start = System.currentTimeMillis();

and at the end do

long end = System.currentTimeMillis();
System.out.println("Method time is: " + (end - start));

but that is:

  1. probably a bunch of work
  2. temporary, and you don't want to muck up your code base

You can instead define aspects that say what methods you want to modify, and that you want to do stuff at the beginning and end of these methods.

When the AOP is applied, either at jar creation time, or class loading time, it's as if you wrote the classes that way originally.