Sunday, March 20, 2011

Writing the Aspect class

Consider our logging class. Which requires to log depending on what method we entered, left etc. whatever user requires. So we have to follow following steps:
  1. Write a class which will contain the common logging code. This is called Aspect.
  2. Either by xml or annotations we will have to configure a pointcut, to specify when(before, after, before return) and where(for all beans or only for a few bean or for a particular method pattern) will this aspect apply.
import org.aspectj.lang.JoinPoint;

//This is an Aspect class
public class LoggingAspect {

//This is an advice.
//Pointcut means where will this advice be applied.
public void log(JoinPoint joinPoint) {
System.out.println("common logging code executed for : "+joinPoint);

Methods of the Aspect class can be logically be called as advices.
We can use annotations or xml to configure the pointcut.
XML configuration for pointcuts
Annotation configuration for pointcuts

No comments:

Post a Comment