what is the AOP in spring boot

Manoj Madushanka
5 min readFeb 5, 2023

ok, In this weekend I will guide you about spring boot AOP and how to use that.

so what is meant by Aspect?

An aspect is simply a piece of code the spring framework execute when you call specific methods inside your application.

Aspect is used for encapsulates cross-cutting concerns such as transaction management, logging, and security in our application.

Spring AOP enables Aspect-Oriented programming in the spring applications.

AOP provides a way to dynamically add the cross-cutting concern before, after, or around the actual logic using simple pluggable configurations. ( inside AOP we are using a proxy design pattern for achieving those functionalities).

AOP helps in separating and maintaining much non-business logic-related code like logging, auditing, security, and transaction management.

AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. It does this by adding additional behavior to existing code without modifying the code itself.

AOP helps us to remove non-business logic from our code and remove that non-business logic to a separate place. It is important to write clear code and understand the logic to new developers.

When we define Aspects or doing configurations, we need to follow WWW (3W s)

those are,

WHAT → Aspect (code or logic we want the sprint to execute when you call a specific method. This is called as aspect)

WHEN → Advice (the spring need to execute the given aspect. for example is it before or after the method call. This is called as Advice.)

WHICH → Pointcut (method inside App that framework needs to intercept and execute the given aspect. this is called as a pointcut)

Other than the above 3W we have another two things to remember those are,

Join point: which defines the event that triggers the execution of an aspect. Inside spring this event is always a method call.

Target object: the bean that declares the method/pointcut which is intercepted by an aspect.

this will help to understand AOP

what is weaving inside AOP?

when we are implementing AOP inside our application using spring boot it will intercept each method call and apply the logic defined in the Aspect.

how does weaving work?

spring boot does this with help of a proxy object. so we try to invoke a method inside a bean spring boot instead of directly giving a reference of the bean instead it will give a proxy object that will manage each call to a method and apply the aspect logic.

(bean is meant by spring boot managed instance of a class)

without AOP vs with AOP

Types of advice in spring boot AOP

@Before: runs before a matched method execution.

@AfterReturning: runs when a matched method execution completes normally

@AfterThrowing: runs when a matched method execution exits by throwing an exception.

@After: runs no matter how a matched method execution exists.

@Around: runs around a matched method execution. It has the opportunity to do work both before and after the method runs and to determine when, how, and even if the method actually gets to run at all.

ok, let’s see how to implement these things in the spring boot application.

We can use the AspectJ pointcut expression to provide details to spring about what kind of methods it needs to intercept by mentioning details around the modifier, return type, name pattern, package name pattern, param pattern, exceptions pattern, etc.

AOP format ( ? means optional )

As a first step to configure our application to use AOP, we need to add the below two dependencies and add @EnableAspectJAutoProxy annotation to our main class or config class.

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.13</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>5.3.13</version>
</dependency>

my main class looks like below.

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

@SpringBootApplication
@EnableAspectJAutoProxy
public class AspectprogrammingApplication {

public static void main(String[] args) {


}

}

then I am going to create the first aspect class to achieve logging cross-cutting functionality.

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.logging.Logger;

@Aspect
@Component
public class LoggerAspect {

private Logger logger = Logger.getLogger(LoggerAspect.class.getName());

/**
* Around means, I need to execute this before and after and inside our pointcut (function)
*
* */
@Around("execution(* com.aspect.aspectprogramming.*.*(..))")
public void logMessage(ProceedingJoinPoint joinPoint) throws Throwable{
// print method signature
logger.info(joinPoint.getSignature().toString()+" method execution begin");
Instant start = Instant.now(); // java 8 feature for record time
// invoking the actual method
joinPoint.proceed();
// after executing method logic
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();
logger.info("Time took to execute the method : "+timeElapsed);
logger.info(joinPoint.getSignature().toString() + " method execution end");

}
}

so what is meant by this “execution(* com.aspect.aspectprogramming.*.*(..))” inside around annotation

check AOP format image above, here I did not mention modifier because it is optional( ? ). * means any here I am saying return type is any. we can see two * marks after aspectprogramming which means any class and any method name. (..) means accept multiple parameters or no parameters.

then we can remove the logging codes of our business logic.

before AOP our Cat class

package com.aspect.aspectprogramming.dao;

import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.logging.Logger;

@Component
public class Cat {
private boolean isAlive = true;
private boolean isHungry;

private Logger logger = Logger.getLogger(Cat.class.getName());

public void feed() {

Instant start = Instant.now();
logger.info("method execution start");

// business logic
if (isAlive) {
isHungry = false;
System.out.println("feeded");
}

logger.info("method execution end");
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();
logger.info("time took to execute method : " + timeElapsed);

}
}

after AOP our Cat class

package com.aspect.aspectprogramming.dao;

import org.springframework.stereotype.Component;

import java.time.Duration;
import java.time.Instant;
import java.util.logging.Logger;

@Component
public class Cat {
private boolean isAlive = true;
private boolean isHungry;

//private Logger logger = Logger.getLogger(Cat.class.getName());

public void feed() {

/*Instant start = Instant.now();
logger.info("method execution start");*/

// business logic
if (isAlive) {
isHungry = false;
System.out.println("feeded");
}

/*logger.info("method execution end");
Instant finish = Instant.now();
long timeElapsed = Duration.between(start, finish).toMillis();
logger.info("time took to execute method : " + timeElapsed);*/

}
}

reference: udemy.com/course/spring-springboot-jpa-hibernate-zero-to-master

--

--