Skip to main content

Aspect Oriented Programming

AOP - Aspect Oriented Programming

In enterprise applications, developers often need to implement cross-cutting concerns such as logging, auditing, security, performance monitoring, and transaction management. Embedding this logic inside every business method leads to duplicate code, poor maintainability, and increased development effort.

Aspect-Oriented Programming (AOP) solves this problem by separating cross-cutting concerns from the core business logic. These concerns are implemented as Aspects, allowing centralized management without modifying the business code.

Real-world Examples
  • Application Logging
  • Auditing
  • Performance Monitoring
  • Security Checks
  • Exception Handling
  • Transaction Management (@Transactional)

AOP Architecture



                Client Request
                      │
                      ▼
                Before Advice
                      │
                      ▼
                Business Method
                      │
         ┌────────────┴────────────┐
         │                         │
         ▼                         ▼
After Returning             After Throwing
         │                         │
         └────────────┬────────────┘
                      ▼
                 After Advice


AOP Terminologies

1. Aspect

An Aspect is a class that contains one or more Pointcuts and Advices. It represents a cross-cutting concern.



@Component
@Aspect
public class LoggingAspect {

}


2. Pointcut

A Pointcut defines where an Advice should execute. It identifies one or more Join Points using AspectJ expressions.

Common Pointcut Expressions

Expression Description
execution() Matches specific method executions.
within() Matches all methods inside a class or package.
this() Matches methods executed on objects implementing a specific type.

Examples



// Match every method inside controller package
@Pointcut(
"execution(* com.alpha.spring.security.user.controller.*.*(..))"
)
public void controllerMethods(){ }


// Match every method inside authentication package
@Pointcut(
"within(com.alpha.spring.security.authentication.*)"
)
public void authenticationPackage(){ }


// Match methods executed on a specific implementation
@Pointcut(
"this(com.alpha.spring.security.user.service.UserDetailsServiceImpl)"
)
public void serviceImplementation(){ }


3. Advice

An Advice defines what action should be executed when a Pointcut is matched.

Advice Execution Time Typical Usage
@Before Before method execution Validation, Logging
@AfterReturning After successful completion Audit, Logging
@AfterThrowing After exception occurs Error Logging
@After Always executes Cleanup
@Around Before and After Performance, Security

4. Join Point

A Join Point is a specific point during program execution where an Aspect can be applied.

Typical Join Points include:

  • Method Execution
  • Constructor Execution
  • Field Access
  • Exception Handling
  • Object Initialization
  • Static Initialization

Examples



// Method execution
execution(* com.example.service.*.*(..))


// Constructor execution
execution(com.example.model.User.new(..))


// Read field
get(* com.example.model.User.name)


// Write field
set(* com.example.model.User.name)


// Exception handler
handler(Exception)


// Object initialization
initialization(* new(..))


// Static initialization
staticinitialization(com.example.model.User)


Logging Aspect Example

The following Aspect demonstrates how centralized logging can be implemented without modifying any controller methods.



@Component
@Aspect
@Slf4j
public class AuthenticationAspect {

    @Pointcut(
    "execution(* com.alpha.spring.security.user.controller.*.*(..))"
    )
    public void loggingPointCut(){}

    @Before("loggingPointCut()")
    public void before(JoinPoint joinPoint){

        log.info(
            "Before : {}",
            joinPoint.getSignature()
        );

    }

    @After("loggingPointCut()")
    public void after(JoinPoint joinPoint){

        log.info(
            "After : {}",
            joinPoint.getSignature()
        );

    }

    @AfterReturning(
        value="loggingPointCut()",
        returning="users"
    )
    public void afterReturning(
            JoinPoint joinPoint,
            List users){

        log.info(
            "Returned : {}",
            users
        );

    }

    @AfterThrowing(
        value="loggingPointCut()",
        throwing="ex"
    )
    public void afterThrowing(
            JoinPoint joinPoint,
            Exception ex){

        log.error(
            "Exception : {}",
            ex.getMessage()
        );

    }

    @Around("loggingPointCut()")
    public Object around(
            ProceedingJoinPoint point)
            throws Throwable{

        long start = System.currentTimeMillis();

        Object result = point.proceed();

        long end = System.currentTimeMillis();

        log.info(
            "Execution Time : {} ms",
            (end-start)
        );

        return result;

    }

}


Custom Annotation Example



@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {

}

Using the custom annotation:


@Before(
"@annotation(com.alpha.spring.security.annotation.CustomAnnotation)"
)
public void annotatedMethod(){

    log.info("Custom Annotation Executed");

}


Advantages of AOP

  • Removes duplicate code
  • Centralized logging
  • Improves maintainability
  • Cleaner business logic
  • Reusable cross-cutting concerns
  • Easy auditing and monitoring
  • Supports declarative transaction management

Interview Tip

Spring internally uses AOP for many important features, including:

  • @Transactional
  • @Cacheable
  • @Async
  • @Secured
  • @PreAuthorize
  • Method Validation

A common interview question is: "How does @Transactional work internally?" The answer is that Spring creates a proxy using AOP. The proxy starts a transaction before the method executes, commits it if the method completes successfully, or rolls it back if an exception occurs.


References

  • https://www.youtube.com/watch?v=POa6ZZKq79E
  • https://reflectoring.io/aop-spring/

Comments

Popular posts from this blog

Spring Boot 4 Ready

Spring Boot 4.x Features Explained:  Java 25, AI Agents, MCP, Resilience, gRPC & Cloud Native Evolution Building on the massive architectural shift introduced in version 3, Spring Boot 4.x bridges the gap between traditional enterprise stability and the rapid demands of modern cloud architecture and AI integration. While Spring Boot 3 introduced the foundations for GraalVM Native Images and Virtual Threads , Spring Boot 4 takes these capabilities mainstream, introduces native resilience patterns, and upgrades the underlying Spring ecosystem. Spring Boot 4 Major Theme: Modern enterprise development with cloud-native architecture, AI integration, improved resilience, better modularity, and optimized JVM performance. Table of Contents 1. Upgraded Foundation & Baselines 2. Built-in Core Resilience Features 3. First-Class Agentic AI & Model Context Protocol (MCP) 4. Native API Versioning Strategy 5. Modern...

Most questions in 2025

Java Spring Boot Senior Engineer Interview Questions & Answers A complete interview preparation guide for Senior Java Engineers, Spring Boot Developers, and Backend Technical Leads covering Java, Spring Boot, Microservices, Cloud, Database, Security, and Performance Engineering concepts. Target Audience: Senior Java Developers Spring Boot Engineers Microservice Architects Backend Technical Leads Table of Contents 1. Describe Yourself 2. RESTful APIs and Standards 3. Latest Spring Boot Version & Features 4. Java Optional 5. WebFlux Reactive Programming 6. WebFlux Retry Mechanism 7. WebFlux Pagination APIs 8. Circuit Breaker 9. Resilience Patterns 10. Rate Limiter 1. Describe Yourself A senior engineer introduction should highlight technical experience, architecture knowledge, ownership, and problem-solving capabilities. Sample Answer I am a Java backend engineer with 7+ years of experience desi...

Data Structure

Java Data Structures A highly-scannable architectural cheat sheet for developers and technical interviews. 1. Linear vs. Non-Linear: The Core Division Data Structure Classification Hierarchy ┌───────────────────────┐ │ Data Structures │ └───────────┬───────────┘ │ ┌───────────────┴───────────────┐ ▼ ▼ ┌────────────────────┐ ┌────────────────────┐ │ Linear (Seq) │ │ Non-Linear │ └──────────┬─────────┘ └──────────┬─────────┘ │ │ ┌──────┴──────┐ ┌──────┴──────┐ ▼ ▼ ▼ ▼ [Static] [Dynamic] [Trees] [Graphs] (Array) (Queue, Stack) (BST) (Network) ...