Layman explanation for somebody who is new to the concepts AOP. This is not exhaustive, but should help in grasping the concepts. If you are already familiar with the basic jargon, you can stop reading now.
Assume you have a normal class Employee and you want to do something every time these methods are called.
class Employee{
public String getName(int id){....}
private int getID(String name){...}
}
these methods are called JoinPoints. We need a way to identify these methods so that the framework can find the methods, among all the classes.methods it has loaded.
So we will write a regular expression to match the signature of these methods. While there is more to it as you will see below, but loosely this regular expression is what defines Pointcut. e.g.
* * mypackage.Employee.get*(*)
First * is for modifier public/private/protected/default.
Second * is for return type of the method.
But then you also need to tell two more things:
- When should an action be taken -
e.g Before/After the method execution OR on exception
- What should it do when it matches (maybe just print a message)
The combination of these two is called Advice.
As you can imagine, you would have to write a function to be able to do #2. So this is how it might look like for the basics.
Note: For clarity, using word REGEX instead of the * * mypackage.Employee.get*(*)
. In reality the full expression goes into the definition.
@Before("execution(REGEX)")
public void doBeforeLogging() {....} <-- executed before the matching-method is called
@After("execution(REGEX)")
public void doAfterLogging() {....} <-- executed after the matching-method is called
Once you start using these quite a bit, you might end up specifying many @After/@Before/@Around advices. The repeated regular expressions will eventually end up making things confusing and difficult to maintain.
So what we do, we just give a name to the expression and use it everywhere else in the Aspect class.
@Pointcut("execution(REGEX)") <-- Note the introduction of Pointcut keyword
public void allGetterLogging(){} <-- This is usually empty
@Before("allGetterLogging")
public void doBeforeLogging() {....}
@After("allGetterLogging")
public void doAfterLogging() {....}
BTW, you would also want to wrap this whole logic in a class, that is called Aspect and you would write a class:
@Aspect
public class MyAwesomeAspect{....}
To get all these things to work, you would have to tell Spring to parse the classes to read, understand and take action on the @ AOP keywords. One way to do it is specifying the following in the spring config xml file:
<aop:aspectj-autoproxy>