Tuesday 23 March 2021

Spring AOP example

 import com.fasterxml.jackson.databind.ObjectMapper;

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.stereotype.Component;

@Component
@Aspect
public class ControllerAOP {

//execution command : <access specifier> <return type> <pacakge.classname.methodname(returntype)>
//example: execution(* com.some.packagename.ClassName.methodname(allarguments))
@Pointcut(value = "execution(public * com.api.*.*.*(..))")
public void controllerPointCut() {}

//A pointcut on a annotation. example: to pointcut on 'Service' annotation
@Pointcut("@within(org.springframework.stereotype.Service)")
public void serviceAnnotationPointCut() {}

@Around(value = "controllerPointCut()")
public Object myAround(ProceedingJoinPoint jp) throws Throwable {

ObjectMapper objectMapper = new ObjectMapper();

System.out.println("Method name :" + jp.getSignature().getName()); // to get method name
System.out.println("Class name : " + jp.getTarget().getClass().getName()); // to get class name
System.out.println("Arguments : " + objectMapper.writeValueAsString(jp.getArgs())); //to get arguments

Object obj = jp.proceed();

System.out.println("Response : " + objectMapper.writeValueAsString(obj)); //to get response body

return obj;
}

@Around(value = "serviceAnnotationPointCut()")
public Object serviceAnnotationAround(ProceedingJoinPoint jp) throws Throwable {

ObjectMapper objectMapper = new ObjectMapper();

System.out.println("Method name :" + jp.getSignature().getName()); // to get method name
System.out.println("Class name : " + jp.getTarget().getClass().getName()); // to get class name
System.out.println("Arguments : " + objectMapper.writeValueAsString(jp.getArgs())); //to get arguments

Object obj = jp.proceed();

System.out.println("Response : " + objectMapper.writeValueAsString(obj)); //to get response body

return obj;
}

}