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.
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.
Practice
(1/5)
1. What is the main purpose of Aspect-Oriented Programming (AOP) in Spring Boot?
easy
A. To separate common tasks like logging and security from business logic
B. To replace the need for writing any business logic
C. To make the application run faster by skipping method calls
D. To store data in the database automatically
Solution
Step 1: Understand AOP's role
AOP helps keep common tasks like logging or security separate from the main business code.
Step 2: Identify the main benefit
This separation makes the code easier to read and maintain without changing the business logic itself.
Final Answer:
To separate common tasks like logging and security from business logic -> Option A
Quick Check:
AOP separates concerns = D [OK]
Hint: AOP separates cross-cutting tasks from main code [OK]
Common Mistakes:
Thinking AOP replaces business logic
Believing AOP speeds up method execution
Confusing AOP with database operations
2. Which of the following is the correct way to define an aspect in Spring Boot using AOP?
easy
A. @Component
public class MyAspect { }
B. @Aspect
public class MyAspect { }
C. @Service
public class MyAspect { }
D. @Repository
public class MyAspect { }
Solution
Step 1: Recognize the annotation for aspects
In Spring AOP, the @Aspect annotation marks a class as an aspect.
Step 2: Confirm the correct syntax
Only @Aspect correctly defines an aspect; @Component alone does not define aspect behavior.
Final Answer:
@Aspect
public class MyAspect { } -> Option B
Quick Check:
@Aspect marks aspect classes = B [OK]
Hint: Use @Aspect to define aspects in Spring Boot [OK]
Common Mistakes:
Using @Component alone without @Aspect
Confusing @Service or @Repository with aspects
Missing the @Aspect annotation
3. Given this Spring Boot aspect code snippet, what will be printed when myService.doWork() is called?
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.MyService.doWork(..))")
public void logBefore() {
System.out.println("Starting work");
}
}
@Service
public class MyService {
public void doWork() {
System.out.println("Doing work");
}
}
medium
A. Starting work
Doing work
B. Doing work
Starting work
C. Doing work
D. Starting work
Solution
Step 1: Understand @Before advice
The @Before advice runs before the target method, so "Starting work" prints first.
Step 2: Trace method call output
Then the actual method prints "Doing work" after the advice.
Final Answer:
Starting work
Doing work -> Option A
Quick Check:
@Before runs before method = A [OK]
Hint: @Before advice runs before method call output [OK]
Common Mistakes:
Assuming advice runs after method
Mixing order of printed lines
Ignoring advice output
4. Identify the error in this Spring Boot aspect code that prevents the advice from running:
@Aspect
@Component
public class SecurityAspect {
@Before("execution(* com.example.MyService.secureMethod())")
public void checkSecurity() {
System.out.println("Checking security");
}
}
@Service
public class MyService {
public void secureMethod(String user) {
System.out.println("Secure method for " + user);
}
}
medium
A. secureMethod should be private
B. Missing @Component annotation on MyService
C. Advice method must return a value
D. The pointcut expression does not match the method signature
Solution
Step 1: Compare pointcut and method signature
The pointcut expects a method with no parameters, but secureMethod takes a String parameter.
Step 2: Understand pointcut matching rules
Because the signature does not match, the advice never runs.
Final Answer:
The pointcut expression does not match the method signature -> Option D
Quick Check:
Pointcut must match method signature = A [OK]
Hint: Match pointcut exactly to method signature [OK]
Common Mistakes:
Ignoring method parameters in pointcut
Thinking @Component missing on service blocks advice
Believing advice must return a value
5. You want to add logging before and after all methods in your service without changing each method. Which AOP approach best achieves this in Spring Boot?
hard
A. Create a new service class that duplicates all methods with logging
B. Manually add logging code inside every service method
C. Use @Before and @After advices with a pointcut matching all service methods
D. Use @Transactional annotation on service methods
Solution
Step 1: Identify the goal
You want to add logging around all service methods without modifying them individually.
Step 2: Choose the correct AOP approach
@Before and @After advices with a pointcut covering all service methods allow running code before and after each method automatically.
Final Answer:
Use @Before and @After advices with a pointcut matching all service methods -> Option C
Quick Check:
AOP advices automate cross-cutting tasks = C [OK]
Hint: Use @Before and @After with pointcut for all methods [OK]
Common Mistakes:
Adding logging manually in every method
Duplicating service classes unnecessarily
Confusing logging with transaction management
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.