Defining custom AOP annotations

In all the examples until now, we have identified methods so that we can apply advice when we're using execution PointCuts.

We can also define custom annotations and use annotation PointCuts to identify methods to apply the advice to.

For example, let's say you found out that there are few specific methods running slowly and you wanted to add advice for detailed logging on them.

One of the implementation approaches is to create a @LogEverything annotation, use the annotation on the methods you want to trace in detail, and define a PointCut matching the annotation.

Defining an annotation is easy:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface LogEverything {
}

We can use @LogEverything on methods that we want to trace, as follows:

@LogEverything
public void placeOrder(int value) {

Before we are able to run the previous example, we need to define the PointCut and advice.

Let's define a common JoinPointConfiguration method for the PointCut. Notice that instead of execution, we are using @annotation in the PointCut:

@Pointcut("@annotation(com.mastering.spring.ch03aopwithspring.LogEverything)")
public void logEverythingAnnoation(){}

Let's define an @Around aspect for logging, as follows. This code is similar to what we did earlier. You can log more details as per your requirements:

@Aspect
@Configuration
public class LogEverythingAspect {

private Logger logger = LoggerFactory.getLogger(this.getClass());

@Around("com.mastering.spring.ch03aopwithspring.JoinPointConfiguration.logEverythingAnnoation()")
public Object calculateMethodExecutionTime(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
logger.info("Method {} started execution", proceedingJoinPoint);
logger.info("Method {} arguments are {}", proceedingJoinPoint, proceedingJoinPoint.getArgs());
Object retVal = proceedingJoinPoint.proceed();
logger.info("Method {} completed execution ", proceedingJoinPoint);
return retVal;
}
}

The result of executing the preceding code is as follows:

gAspect$$EnhancerBySpringCGLIB$$57feda03 : Method execution(void com.mastering.spring.ch03aopwithspring.OrderDao.placeOrder(int)) started execution
gAspect$$EnhancerBySpringCGLIB$$57feda03 : Method execution(void com.mastering.spring.ch03aopwithspring.OrderDao.placeOrder(int)) arguments are [20]
//Other Log
gAspect$$EnhancerBySpringCGLIB$$57feda03 : Method execution(void com.mastering.spring.ch03aopwithspring.OrderDao.placeOrder(int)) completed execution

You can see that we added the complete logging around this method execution.

You can add @LogEverything to all the methods you want to be able to trace completely.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset