Spring Boot - AOP(Aspect Oriented Programming)

Last Updated : 30 Mar, 2026

Aspect Oriented Programming (AOP) is a programming approach used to separate cross-cutting concerns such as logging, security, and transactions from the main business logic. It improves code modularity and maintainability.

  • Separates cross-cutting concerns from business logic.
  • Reduces code duplication across multiple layers.
  • Adds new behavior without modifying existing code.
dominant-frameworks-in-AOP

The aspect class provides us the flexibility to:

  • Single Class for Concerns : Common concerns are defined in one aspect class instead of spreading across the code.
  • Clean Business Logic : Business layer contains only main logic while secondary concerns are handled by aspects.

AOP Terminologies

Aspect-Oriented Programming (AOP) uses specific terminologies to define how cross-cutting concerns like logging and security are applied in an application. These terms help manage additional behaviors separately from the main business logic.

  • Aspect: A module that contains cross-cutting concerns such as logging or security.
  • Advice: The action or code that runs at a specific point during program execution.
Advice-in-AOP
TerminologyExplanation
AspectA class that contains cross-cutting concerns like logging or security. Declared using @Aspect.
AdviceCode executed before or after a method. Types: Before, After, After-Returning, After-Throwing, Around.
PointcutExpression that defines where the advice should be applied.
Join PointA point in the program where AOP can be applied (e.g., method execution).
Target ObjectThe object whose method is being advised by AOP.
ProxyA proxy object created by Spring to apply advice to the target object at runtime.
WeavingThe process of linking aspects with the application code.

Why do we need AOP?

In applications, some functionalities like logging, security, caching, and validation are used in many modules. These are called cross-cutting concerns.

  • Avoids repeating common logic across classes.
  • Keeps business logic clean and focused.
  • Improves code maintainability and modularity.

Implementing cross-cutting concerns in every module makes the code lengthy and hard to manage. Aspect-Oriented Programming (AOP) solves this by placing these concerns in a separate aspect and applying them at specific points using pointcuts.

Example: Logging Aspect example

Java
@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void logBefore(){
        System.out.println("Method execution started");
    }

    @After("execution(* com.example.service.*.*(..))")
    public void logAfter(){
        System.out.println("Method execution completed");
    }
}
Comment