Integrating Spring AOP with AEM

03 / Aug / 2015 by Yagyesh 0 comments

Spring AOP

Spring AOP (Aspect-oriented programming) framework is used to modularize cross-cutting concerns in aspects.Some of cases where we can use it are to control some of common things like logging , adding some extra feature without actually touching the core logic.

This blog post will explain how to enable aspects in our AEM projects using aspectj-maven-plugin.
Below are the steps for various configuration we need to make.

Configuration at pom level

In plugin section add following lines of code


In dependency section add

    <!-- Day CQ5 WCM Dependencies -->
    <!-- Apache Sling Dependencies -->
    <!-- Apache Jackrabbit/JCR Dependencies -->

The Aspect class need to placed under folder src/main/aspect.
sample project structure


Below is the sample class which is used to log messages whenever the execution of method starts and end for all java classes methods that are inside the package com.ig

package com.ig.aspects;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LoggerAspect {

	@Pointcut(value = "execution(public * com.ig.core.*.*(..))")
	public void anyMethod() {

	@Before(value = "anyMethod()")
	public void logEntry(JoinPoint joinPoint) {
		Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());"Method Started...."+joinPoint.getSignature().getName()+"()");

	@After(value = "anyMethod()")
	public void logExit(JoinPoint joinPoint) {
		Logger logger = LoggerFactory.getLogger(joinPoint.getTarget().getClass());" Method Exited..."+joinPoint.getSignature().getName()+"()");

execution(public * com.ig.core.*.*(..)) : the execution of any method defined in the core package or a sub-package
@Before Before advice It will execute before the method execution
@After After returning advice tt will execute after the method is returned a result.

Refer Spring’s AOP documentation for Joint Point, Advice, Pointcuts, etc. and depending upon the use case in your application select the right one.



Leave a comment -