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">
<aop:aspectj-autoproxy /> </beans>
|
Create Aspect
Add Logging Aspect
1 2 3 4 5 6
| @Aspect @Component public class CRMLoggingAspect { 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
| @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){ String methodName = joinPoint.getSignature().toShortString(); logger.info("========>> in @Before: Method Name: " + methodName); 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){ 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)