For basics of AOP refer
http://kamalmeet.com/aop/aspect-oriented-programming/
http://kamalmeet.com/aop/aspect-oriented-programming-implementation/
Here is a simple logging example using aspectj
package com.my.aspect;
import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;
/**
* This is class implementing logging aspect. This is a generic class which can
* be embedded into any piece of code for implementing logging.
*
* @author kamalmeet
* @version 1.0
*/
@Component
@Aspect
public class LoggingAspect {
private static final Logger LOG = Logger.getLogger(LoggingAspect.class);;
private static final String POINT_CUT = "execution(* com.my.package.*.*(..))";
/**
* This method is used to log action before entering into point-cut method.
*
* @param joinPoint
*/
// @Before(POINT_CUT)
@Before(POINT_CUT)
public void logBefore(JoinPoint joinPoint) {
LOG.info("Entering function: "+ joinPoint.getSignature());
}
/**
* This method is used to log action after returning from point-cut method.
*
* @param joinPoint
*/
@AfterReturning(POINT_CUT)
public void logAfterReturing(JoinPoint joinPoint) {
LOG.info("Exiting successfully from function: "+
joinPoint.getSignature());
}
/**
* This method is used to log error in case some exception condition
* occurred in the given point-cut method.
*
* @param joinPoint
*/
@AfterThrowing(POINT_CUT)
public void logAfterThrowing(JoinPoint joinPoint) {
LOG.error("Exiting with exception thrown from function: "+
joinPoint.getSignature());
}
}
