Skip to main content

Aspect-Oriented Programming (AOP)

In enterprise applications, certain logical responsibilities inherently span across multiple layers of code. Examples include:

  • Logging: Printing method execution times across all services.
  • Security Check: Verifying JWT tokens before evaluating Controller logic.
  • Transactions: Opening and closing database connections.

These responsibilities are called "Cross-Cutting Concerns." If you manually implement logging inside every single method of your application, your code becomes heavily polluted and difficult to maintain.

Aspect-Oriented Programming (AOP) solves this by isolating these cross-cutting concerns into a modular unit called an "Aspect".

AOP Terminology

  1. Aspect: The modularized class containing the cross-cutting logic (e.g., a LoggingAspect class).
  2. Advice: The actual action executing. Defined by when it fires: @Before, @After, @Around.
  3. Pointcut: An expression that strictly targets where the Advice should execute (e.g., "Target all methods securely executing inside the service package").
  4. Join Point: The actual execution point precisely during runtime (a specific method execution).

Basic AOP Implementation

To implement AOP in Spring Boot, define a class with @Aspect and specify the execution paths.

@Component
@Aspect
public class LoggingAspect {

// Pointcut expression targeting ALL methods inside the 'service' package
@Before("execution(* com.codenbuild.service.*.*(..))")
public void logBeforeMethodExecution(JoinPoint joinPoint) {
String methodName = joinPoint.getSignature().getName();
System.out.println("Executing Method: " + methodName);
}
}

In the example above, Spring uses completely hidden background proxies automatically. When your code calls a service method natively, Spring intercepts the call seamlessly, runs the logBeforeMethodExecution method dynamically, and then continues on to your actual service logic correctly.