🧠 AOP in Spring Boot

What Is AOP?

AOP (Aspect-Oriented Programming) is a programming paradigm that helps separate cross-cutting concerns — logic that’s common across multiple parts of an application, like:

  • Logging
  • Security
  • Transactions
  • Performance monitoring
  • Caching

Rather than duplicating this code across methods, AOP allows you to write it once and apply it where needed.


💡 Core Concepts of AOP

Concept Meaning
Aspect A module containing cross-cutting logic
Advice Action taken at a point in program execution (e.g., before/after method execution)
Join Point A point during execution (usually a method call)
Pointcut A predicate that matches join points (like a method name pattern)
Weaving Linking aspects with application code at runtime

🧪 Example: Logging with AOP in Spring Boot


1. Add Dependency (if using Spring Boot Starter)

If using Spring Boot, spring-boot-starter-aop is usually included. Otherwise, add:

<!-- pom.xml -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

2. Create the Aspect

@Aspect
@Component
public class LoggingAspect {

    @Before("execution(* com.certifikation.service.*.*(..))")
    public void logBeforeMethod(JoinPoint joinPoint) {
        System.out.println("Method Called: " + joinPoint.getSignature().getName());
    }

    @AfterReturning(pointcut = "execution(* com.certifikation.service.*.*(..))", returning = "result")
    public void logAfterMethod(JoinPoint joinPoint, Object result) {
        System.out.println("Method Returned: " + joinPoint.getSignature().getName() + " -> " + result);
    }
}


3. Enable AspectJ Auto Proxying (optional)

If not already enabled:

@SpringBootApplication
@EnableAspectJAutoProxy
public class MyApp {
    public static void main(String[] args) {
        SpringApplication.run(MyApp.class, args);
    }
}

🧵 Pointcut Expressions – Quick Reference

Expression Matches
execution(* com.app..*.*(..)) All methods in the package and subpackages
execution(public * *(..)) Any public method
execution(* get*(..)) Methods starting with "get"

📌 Real-World Use Cases

✅ Logging method calls and responses
✅ Validating input data
✅ Measuring execution time
✅ Securing endpoints (auth checks)
✅ Applying caching policies


🧠 Summary

Spring Boot makes it super easy to integrate AOP and cleanly separate repetitive logic like logging, auditing, or metrics. This leads to cleaner, modular, and maintainable code.

✨ Write logic once. Apply it everywhere.

Back to blog

Leave a comment