AOP helps add logging to your app without changing your main code. It keeps your code clean and easy to read.
AOP for logging in Spring Boot
@Aspect @Component public class LoggingAspect { @Before("execution(* com.example..*(..))") public void logBefore(JoinPoint joinPoint) { // logging code here } @AfterReturning(pointcut = "execution(* com.example..*(..))", returning = "result") public void logAfter(JoinPoint joinPoint, Object result) { // logging code here } }
@Aspect marks the class as an aspect for AOP.
@Before runs code before matched methods; @AfterReturning runs after methods return.
@Before("execution(* com.example.service.*.*(..))") public void logBeforeMethod(JoinPoint joinPoint) { System.out.println("Starting: " + joinPoint.getSignature().getName()); }
@AfterReturning(pointcut = "execution(* com.example.controller.*.*(..))", returning = "result") public void logAfterMethod(JoinPoint joinPoint, Object result) { System.out.println("Finished: " + joinPoint.getSignature().getName() + ", returned: " + result); }
This Spring Boot app uses AOP to log before and after the add method in CalculatorService. The logs show method start, finish, and return value.
package com.example.aoplogging; import org.aspectj.lang.JoinPoint; import org.aspectj.lang.annotation.AfterReturning; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class LoggingAspect { @Before("execution(* com.example.aoplogging.service.*.*(..))") public void logBefore(JoinPoint joinPoint) { System.out.println("[LOG] Starting method: " + joinPoint.getSignature().getName()); } @AfterReturning(pointcut = "execution(* com.example.aoplogging.service.*.*(..))", returning = "result") public void logAfter(JoinPoint joinPoint, Object result) { System.out.println("[LOG] Finished method: " + joinPoint.getSignature().getName() + ", returned: " + result); } } package com.example.aoplogging.service; import org.springframework.stereotype.Service; @Service public class CalculatorService { public int add(int a, int b) { return a + b; } } package com.example.aoplogging; import com.example.aoplogging.service.CalculatorService; import org.springframework.boot.CommandLineRunner; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.EnableAspectJAutoProxy; @SpringBootApplication @EnableAspectJAutoProxy public class AopLoggingApplication { public static void main(String[] args) { SpringApplication.run(AopLoggingApplication.class, args); } @Bean public CommandLineRunner run(CalculatorService calculatorService) { return args -> { int result = calculatorService.add(5, 3); System.out.println("Result: " + result); }; } }
Make sure to add @EnableAspectJAutoProxy in your Spring Boot main class or config.
Use pointcut expressions carefully to target only the methods you want to log.
Logging too much can slow your app, so log only important methods.
AOP lets you add logging without changing your main code.
Use @Before and @AfterReturning to log method start and end.
Keep your code clean and separate from logging details.
Practice
Solution
Step 1: Understand AOP's role in logging
AOP allows adding extra behavior like logging without modifying the main code logic.Step 2: Identify the benefit of separation
By using AOP, logging code is kept separate, making the main code cleaner and easier to maintain.Final Answer:
To add logging without changing the main business code -> Option CQuick Check:
AOP adds logging cleanly = A [OK]
- Thinking AOP replaces logging frameworks
- Believing logging must be written inside each method
- Assuming AOP disables logging automatically
Solution
Step 1: Recall Spring AOP annotations
@Before runs advice before the target method executes, perfect for logging method start.Step 2: Differentiate from other annotations
@AfterReturning runs after method success, @Around wraps method, @AfterThrowing runs on exceptions.Final Answer:
@Before -> Option DQuick Check:
Log before method = @Before [OK]
- Confusing @Before with @AfterReturning
- Using @AfterThrowing for normal logging
- Thinking @Around is only for exceptions
processOrder() method completes successfully?@Before("execution(* com.example.service.*.*(..))")
public void logStart() {
System.out.println("Method started");
}
@AfterReturning("execution(* com.example.service.*.*(..))")
public void logEnd() {
System.out.println("Method completed");
}Solution
Step 1: Analyze @Before advice
BeforeprocessOrder()runs, "Method started" is printed.Step 2: Analyze @AfterReturning advice
After successful completion, "Method completed" is printed.Final Answer:
Method started and Method completed -> Option AQuick Check:
Before + AfterReturning logs both messages [OK]
- Thinking only one advice runs
- Confusing @AfterReturning with @AfterThrowing
- Assuming no logs if method returns void
@Before("execution(* com.example..*(..))")
public void logStart() {
System.out.println("Starting method");
}
@AfterReturning("execution(* com.example.service.*.*(..))")
public void logEnd() {
System.out.println("Method ended");
}Solution
Step 1: Check pointcut expressions
@Before targets "com.example..*" (all subpackages), @AfterReturning targets only "com.example.service.*".Step 2: Understand mismatch impact
This mismatch means @Before runs on more methods than @AfterReturning, causing inconsistent logging.Final Answer:
The pointcut expressions target different packages -> Option AQuick Check:
Pointcut mismatch = A [OK]
- Assuming pointcut syntax is wrong
- Thinking return type is required in advice methods
- Believing @AfterReturning must have returning attribute always
com.example.service. Which combination of Spring AOP advice annotations should you use?Solution
Step 1: Identify logging needs
Entry logging requires @Before, exit logging requires @AfterReturning, exception logging requires @AfterThrowing.Step 2: Confirm combined advice usage
Using all three annotations covers all cases: start, successful end, and exceptions.Final Answer:
@Before, @AfterReturning, and @AfterThrowing -> Option BQuick Check:
All logging cases need these three advices [OK]
- Using only @Before and @AfterReturning misses exceptions
- Thinking @Around alone is simpler for all cases
- Ignoring exception logging with @AfterThrowing
Ready to prove it?
Pass the test and this pattern moves unknown
