AOP is used for implementing Cross Cutting Concern. What is Cross Cutting Concern ? The items which can be used across all layers of an application like – data layer, business layer or web layer, are called Cross Cutting Concern. For eg., Logging, Security, measuring performance, these are the things which are not limited to a particular layer, its span across all layers, these are called Cross Cutting Concerns.
Lets see a demo on AOP using a Spring Boot application. We will create a CRUD application using Spring Boot, JPA and H2 database. You can refer this tutorial for creating the same, where we have used Gradle but here will be using Mavel as the build tool.
Here we will not discuss about how to create the CRUD application.
After creating the CRUD application follow the below steps.
Create a Aspect class like below. Annotate it with @Aspect, Add @Component annotation so that Spring Boot auto configuration can pick it up.
Now if we want to intercept a particular class/method, we have to add Pointcut, Advice and Joinpoint as shown below :
package com.heapsteep.aop; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @Aspect @Component public class MyAspect { Logger logger = LoggerFactory.getLogger(MyAspect.class); @Before("execution(* com.heapsteep.controller.MyController.*(..))") //Pointcut public void beforeAdvice(JoinPoint joinPoint) { //JoinPoint logger.info("Intercepted {} method calls...", joinPoint.getSignature()); //Advice } }
So, whenever any of the methods of the MyController class will be called before that the above Pointcut will be called.
Below is a diagram describing about what is the meaning of various components in @Before pointcut :
Once you call the endpoint of addPerson(), you can see see below message in the console log:
Intercepted Person com.heapsteep.controller.MyController.addPerson(Person) method calls...
Below are some of the terms that we use in AOP:
Joinpoint – the specific method that is intercepted.
PointCut – eg., @Before(“execution(* com.heapsteep..(..))”)
Advice – the steps to execute when we intercept the Joinpoint.
Aspect – combination of Pointcut and Advice
Weaving – the process which weave these things around your code is called weaving.
Weaver – the AOP framework, which does all these weavings.
Similarly we can add @After Pointcut which will be called after the respective method is called.
There are some more Pointcuts like @Around, @AfterReturning, @AfterThrowing, etc.
Source code of the above AOP demo: https://github.com/heapsteep/aop-demo.git