AOP:Add Logging to Spring MVC Project

Last Updated on: February 8, 2021 pm

AOP: Add Logging to Spring MVC Project

Add AspectJ JAR Files

Add AspectJ JAR file to web/WEB-INF/lib/aspectjweaver-1.8.13.jar

Enable AspectJ Auto Proxy

Add AspectJ Auto Proxy to spring-mvc-crud-demo-servlet.xml

1
2
3
4
5
6
7
8
9
10
11
<beans ...
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
...
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">

<!-- Add AspectJ Autoproxy support for AOP-->
<!-- This is used for processing @Aspect classes -->
<aop:aspectj-autoproxy />
</beans>

Create Aspect

Add Logging Aspect

1
2
3
4
5
6
@Aspect
@Component
public class CRMLoggingAspect {
// setup logger
private Logger logger = Logger.getLogger(getClass().getName());
}

Setup Pointcut Declaration

Create three seperate PointCut Declaration and join them together.

1
2
3
4
5
6
7
8
9
10
11
12
// setup pointcut declarations
@Pointcut("execution(* com.luv2code.springdemo.controller.*.*(..))")
private void forControllerPackage(){ }

@Pointcut("execution(* com.luv2code.springdemo.dao.*.*(..))")
private void forDaoPackage(){ }

@Pointcut("execution(* com.luv2code.springdemo.service.*.*(..))")
private void forServicePackage(){ }

@Pointcut("forControllerPackage() || forDaoPackage() || forServicePackage()")
private void forAppFlow(){}

Add @Before Advice

1
2
3
4
5
6
7
8
9
10
11
@Before(value = "forAppFlow()")
public void beforeAdvice(JoinPoint joinPoint){
// display the method name
String methodName = joinPoint.getSignature().toShortString();
logger.info("========>> in @Before: Method Name: " + methodName);
// display the args of the method
Object[] args = joinPoint.getArgs();
for(Object o: args){
logger.info("========>> Argument: "+ o.toString());
}
}

Add @AfterReturning Advice

1
2
3
4
5
6
7
8
9
@AfterReturning(
pointcut = "forAppFlow()",
returning = "res")
public void afterReturning(JoinPoint joinPoint, Object res){
// display the method name
String methodName = joinPoint.getSignature().toShortString();
logger.info("========>> in @AfterReturning: Method Name: " + methodName);
logger.info("========>> Result: "+ res);
}

Log Example

Reference: [1]Udemy, Spring & Hibernate for Beginners (including SpringBoot)