Skip to main content

Command Palette

Search for a command to run...

Discover Spring AOP: Logging, Practical Examples, and Use Cases Explained

Updated
3 min read
Discover Spring AOP: Logging, Practical Examples, and Use Cases Explained

If you’ve ever found yourself adding the same logging, security checks, or performance metrics across multiple methods in your Spring Boot application, you might want to consider Spring AOP. It’s a powerful tool that allows you to separate cross-cutting concerns from your business logic, keeping your code cleaner and more maintainable.

In this post, we’ll explore:

  • What Spring AOP is

  • Real-world use cases

  • Hands-on code examples

  • Tips for production-ready AOP


What is AOP?

Aspect-Oriented Programming (AOP) is about injecting behavior into existing code without modifying it directly.

Instead of adding logging, security, or metrics into each method, you define it once as an Aspect, and Spring applies it wherever it matches a pointcut.

Key concepts:

  • Aspect: A module with cross-cutting logic (e.g., logging, metrics)

  • Join Point: A point in your code execution (usually method calls)

  • Advice: The actual code executed (before, after, around)

  • Pointcut: Expression to select join points

  • Weaving: The process of applying aspects to your code


Real-World Use Case: Logging Controller Methods

Imagine you want to log every API call to your controllers, including method name, parameters, and execution time. Instead of adding logging statements everywhere, you can do it cleanly with AOP.


Step 1: Add Spring AOP Dependency

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

Step 2: Create a Sample Controller

@RestController
@RequestMapping("/api/users")
public class UserController {

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id) throws InterruptedException {
        Thread.sleep(200); // Simulate delay
        return "User with ID: " + id;
    }

    @PostMapping
    public String createUser(@RequestBody String user) {
        return "Created user: " + user;
    }
}

Step 3: Define a Logging Aspect

@Aspect
@Component
@Slf4j
public class LoggingAspect {

    @Pointcut("execution(* com.example.demo..*Controller.*(..))")
    public void controllerMethods() {}

    @Around("controllerMethods()")
    public Object logExecutionDetails(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        String method = joinPoint.getSignature().toShortString();
        Object[] args = joinPoint.getArgs();

        log.info("➡️ Entering {} with args {}", method, Arrays.toString(args));

        Object result = joinPoint.proceed();

        long duration = System.currentTimeMillis() - start;
        log.info("⬅️ Exiting {} executed in {} ms", method, duration);

        return result;
    }
}

Output Example

Hitting /api/users/1 produces:

➡️ Entering UserController.getUser(..) with args [1]
⬅️ Exiting UserController.getUser(..) executed in 205 ms

No repeated logging code in your controllers — clean and maintainable. ✅


Other Use Cases for Spring AOP

  • Security: Validate roles or tokens before method execution

  • Performance Metrics: Track method execution time

  • Transaction Auditing: Automatically log database changes

  • Exception Handling: Centralized logging of errors

  • Caching: Dynamically intercept methods for caching logic


Pro Tips for Production

  • Keep pointcuts specific to avoid unexpected advice application

  • Use annotations like @Loggable for flexible targeting

  • Prefer @Around advice for full control over execution

  • Don’t overuse AOP — it’s a tool for cross-cutting concerns, not business logic


Bonus: Annotation-Based Logging

Define a custom annotation:

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

Use it in your controller:

@GetMapping("/{id}")
@Loggable
public String getUser(@PathVariable Long id) {
    return "User with ID: " + id;
}

Update your aspect:

@Pointcut("@annotation(com.example.demo.aop.Loggable)")
public void loggableMethods() {}

Now only annotated methods are intercepted — more control, less noise.


Conclusion

Spring AOP is a must-know feature for any serious Spring developer. It allows you to handle cross-cutting concerns elegantly and keeps your core logic clean.

Try it for logging, security, metrics, and auditing — your future self will thank you.