AspectJ for performance monitoring in Spring

Aspects in general allow you to „weave“ code into classes from the outside. This is like decorating a class, only on class file level. The code can be woven in on load-time (ltw, when the class is loaded into the jvm) or on compile-time.

The idea is to add external functionality without being invasive in the existing code, which can be helpful for legacy code, or for logging purposes, to not pollute the whole code. Downside: you don’t have all your code in one class anymore and the more Aspects you apply, the more confusing it might get, so apply them wisely.

Short notice: There is a difference between Spring AOP and AspectJ.
Spring can also apply Aspects, but uses runtime-weaving, which creates proxy objects and adds a lot of overhead that we don’t need.

This is the code for our performance monitoring:

import java.util.logging.Level;
import java.util.logging.Logger;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.context.annotation.EnableLoadTimeWeaving;

public class ExecuTimeLogger {

	 * Pointcut to select all public methods in all classes of a sub package, so
	 * the advice will be called for all the methods.
	@Pointcut("execution(* com.web.controller.Controller.*(..))")
	public void selectControllerMethods() {

	public Object logTime(ProceedingJoinPoint thisJoinPoint) throws Throwable {
		final long start, end;
		Object[] args = thisJoinPoint.getArgs();
		start = System.nanoTime();
		Object result = thisJoinPoint.proceed(args);
		end = System.nanoTime();
		 Logger.getLogger(TimeLogger.class.getName()).log( Level.WARNING,
		 "Method: " + thisJoinPoint.getSignature() + " " + (end - start) / 1000 / 1000 + " ms");
		return result;

The @pointcut annotated method defines the expression to select the methods we want to weave into.

The @Around annotated method is the logic that is executed.

More information and details explanations can be found here:

Kommentar verfassen

Trage deine Daten unten ein oder klicke ein Icon um dich einzuloggen:

Du kommentierst mit Deinem Abmelden /  Ändern )


Du kommentierst mit Deinem Twitter-Konto. Abmelden /  Ändern )


Du kommentierst mit Deinem Facebook-Konto. Abmelden /  Ändern )

Verbinde mit %s