📖 Scenario: You are building a Spring Boot application where you want to log method calls automatically without adding logging code inside each method. This helps keep your code clean and makes it easier to track what methods are called and when.
🎯 Goal: Create an Aspect using Spring AOP that logs the start and end of method executions in a service class.
📋 What You'll Learn
Create a service class called MyService with a method performTask that returns a string.
Create an Aspect class called LoggingAspect that logs before and after the performTask method runs.
Use Spring AOP annotations like @Aspect, @Before, and @After.
Print log messages to the console indicating when the method starts and ends.
💡 Why This Matters
🌍 Real World
Logging method calls automatically helps developers track application behavior without cluttering business logic with print statements.
💼 Career
Understanding AOP and logging is important for building maintainable Spring Boot applications and is a common task in backend development roles.
Progress0 / 4 steps
1
Create the service class
Create a Spring service class called MyService with a public method performTask that returns the string "Task Completed".
Spring Boot
Hint
Use @Service annotation on the class and define the method exactly as public String performTask().
2
Create the logging aspect class
Create an Aspect class called LoggingAspect annotated with @Aspect and @Component. Define a pointcut that matches the execution of performTask method in MyService.
Spring Boot
Hint
Use @Pointcut with the expression execution(* MyService.performTask(..)) to match the method.
3
Add logging before and after method execution
In the LoggingAspect class, add a @Before advice method that prints "Starting performTask" and an @After advice method that prints "Finished performTask". Both advices should use the performTaskPointcut() pointcut.
Spring Boot
Hint
Use @Before and @After annotations on methods that print the required messages.
4
Run and verify logging output
Write a main method in a Spring Boot application class that gets the MyService bean from the application context and calls performTask(). Run the application and verify the console output shows Starting performTask, then Finished performTask, and finally the returned string Task Completed.
Spring Boot
Hint
Use SpringApplication.run to start the app, get MyService bean, call performTask(), and print the result.
Practice
(1/5)
1. What is the main purpose of using AOP (Aspect-Oriented Programming) for logging in Spring Boot?
easy
A. To write logging code inside every method manually
B. To replace all existing logging frameworks
C. To add logging without changing the main business code
D. To disable logging for all methods automatically
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 C
Quick Check:
AOP adds logging cleanly = A [OK]
Hint: AOP separates logging from business code [OK]
Common Mistakes:
Thinking AOP replaces logging frameworks
Believing logging must be written inside each method
Assuming AOP disables logging automatically
2. Which annotation is used in Spring AOP to execute code before a method runs for logging purposes?
easy
A. @AfterReturning
B. @AfterThrowing
C. @Around
D. @Before
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 D
Quick Check:
Log before method = @Before [OK]
Hint: Use @Before to log method start [OK]
Common Mistakes:
Confusing @Before with @AfterReturning
Using @AfterThrowing for normal logging
Thinking @Around is only for exceptions
3. Given this Spring AOP advice snippet, what will be logged when 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");
}
medium
A. Method started and Method completed
B. Method completed only
C. Method started only
D. No output logged
Solution
Step 1: Analyze @Before advice
Before processOrder() 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 A
Quick Check:
Before + AfterReturning logs both messages [OK]
Hint: Both @Before and @AfterReturning run on success [OK]
Common Mistakes:
Thinking only one advice runs
Confusing @AfterReturning with @AfterThrowing
Assuming no logs if method returns void
4. Identify the error in this Spring AOP logging advice code:
@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");
}
medium
A. The pointcut expressions target different packages
B. The method signatures lack return types
C. The @AfterReturning advice is missing a returning attribute
D. The pointcut expression in @Before is invalid
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 A
Quick Check:
Pointcut mismatch = A [OK]
Hint: Match pointcut packages exactly for consistent logging [OK]
Common Mistakes:
Assuming pointcut syntax is wrong
Thinking return type is required in advice methods
Believing @AfterReturning must have returning attribute always
5. You want to log method entry, exit, and exceptions for all service methods in package com.example.service. Which combination of Spring AOP advice annotations should you use?