0
0
Spring Bootframework~5 mins

Why AOP matters in Spring Boot

Choose your learning style9 modes available
Introduction

AOP helps keep your code clean by separating common tasks from your main logic. It makes your app easier to manage and change.

When you want to log actions across many parts of your app without repeating code.
When you need to check user permissions before running certain functions.
When you want to handle errors in a consistent way everywhere.
When you want to measure how long parts of your app take to run.
When you want to add extra behavior to methods without changing their code.
Syntax
Spring Boot
@Aspect
@Component
public class MyAspect {

    @Before("execution(* com.example.service.*.*(..))")
    public void beforeMethod() {
        // code to run before methods
    }

}
Use @Aspect to mark a class as an aspect that holds extra behaviors.
Use @Before, @After, or @Around to run code at different times around method calls.
Examples
This runs before any method in the service package.
Spring Boot
@Before("execution(* com.example.service.*.*(..))")
public void logBefore() {
    System.out.println("Method is about to run");
}
This runs after methods return successfully and can access the result.
Spring Boot
@AfterReturning(pointcut = "execution(* com.example.service.*.*(..))", returning = "result")
public void logAfter(Object result) {
    System.out.println("Method returned: " + result);
}
This wraps the method call to measure how long it takes.
Spring Boot
@Around("execution(* com.example.service.*.*(..))")
public Object measureTime(ProceedingJoinPoint joinPoint) throws Throwable {
    long start = System.currentTimeMillis();
    Object result = joinPoint.proceed();
    long time = System.currentTimeMillis() - start;
    System.out.println("Method took " + time + " ms");
    return result;
}
Sample Program

This Spring Boot app uses AOP to measure how long the greet method takes. The aspect prints the time, and the main app prints the greeting.

Spring Boot
package com.example.demo;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TimingAspect {

    @Around("execution(* com.example.demo.MyService.*(..))")
    public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        Object result = joinPoint.proceed();
        long duration = System.currentTimeMillis() - start;
        System.out.println(joinPoint.getSignature() + " took " + duration + " ms");
        return result;
    }
}

package com.example.demo;

import org.springframework.stereotype.Service;

@Service
public class MyService {
    public String greet(String name) {
        try {
            Thread.sleep(100); // simulate work
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return "Hello, " + name;
    }
}

package com.example.demo;

import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@ComponentScan("com.example.demo")
public class DemoApplication implements CommandLineRunner {

    private final MyService myService;

    public DemoApplication(MyService myService) {
        this.myService = myService;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        String message = myService.greet("World");
        System.out.println(message);
    }
}
OutputSuccess
Important Notes

AOP helps keep your main code simple and focused on its job.

Be careful with performance: aspects add a small overhead.

Use clear pointcut expressions to target only the methods you want.

Summary

AOP separates common tasks like logging or security from business code.

It runs extra code before, after, or around methods without changing them.

This makes your app easier to read, maintain, and update.