What is Spring AOP?

Spring AOP (Aspect Oriented Programming) is a programming pattern used to increase modularity by allowing the separation of the cross-cutting concern. This can be different from business logic. We can add our additional logic.

Spring IoC container does not depend on AOP so we can skip AOP from our SpringBoot application. AOP complements Spring IoC to provide a competent middleware solution.

Spring AOP provides declarative services for us, One of the examples of such service is @Transactional annotation. It also allows us to build custom aspects and utilize the power of AOP in our application.

Following are the AOP basic terminologies:

JoinPoint

  • Simply put, a JoinPoint is a point in the execution flow of a method where an Aspect (new behavior) can be plugged in.

Advice

  • It’s the behavior that addresses system-wide concerns (logging, security checks, etc…). 
  • This behavior is represented by a method to be executed at a JoinPoint.
  • This behavior can be executed Before, After, or Around the JoinPoint according to the Advice type as we will see later.

Pointcut

  • A Pointcut is an expression that defines at what JoinPoints a given Advice should be applied.

Aspect

  • Aspect is a class in which we define Pointcuts and Advices.

Let’s see a SpringBoot example for the AOP..

  • To implement AOP we need to add the following dependency in our application.
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>
  • Now let’s create our custom annotation which we will use to log the data in our application.
  • We used the expression @Pointcut(“@annotation(CustomLogging)”) to describe which potential methods (JoinPoints) are affected by the corresponding Advice method. 
  • In our example, we want to add advice to all methods that are annotated with our @CustomLogging annotation.
  • We have added @Before(“loggingPointcut()”) which executes the annotated method logAllMethodCallsAdvice before the execution of any method annotated with @CustomLogging.
  • Following is an example of the same.

-A blog by Shwetali Khambe

Related Posts