0
0
Spring Bootframework~30 mins

@After and @AfterReturning in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using @After and @AfterReturning in Spring Boot
📖 Scenario: You are building a simple Spring Boot application that logs messages after a service method runs. This helps track when methods finish and what results they return.
🎯 Goal: Create an aspect class that uses @After to log a message after a method runs, and @AfterReturning to log the returned value from the method.
📋 What You'll Learn
Create a service class with a method getMessage() that returns a string
Create an aspect class with @After advice that logs after getMessage() runs
Add @AfterReturning advice in the aspect to log the returned string from getMessage()
Use Spring AOP annotations and proper pointcut expressions
💡 Why This Matters
🌍 Real World
Logging method execution and returned values helps monitor application behavior and debug issues in real Spring Boot applications.
💼 Career
Understanding Spring AOP annotations like @After and @AfterReturning is essential for backend developers working with Spring Boot to implement cross-cutting concerns like logging and auditing.
Progress0 / 4 steps
1
Create the service class with getMessage() method
Create a Spring service class called SimpleService with a public method getMessage() that returns the string "Hello from service".
Spring Boot
Need a hint?

Use @Service annotation and define getMessage() to return the exact string.

2
Create the aspect class with @After advice
Create an aspect class called LoggingAspect annotated with @Aspect and @Component. Add an @After advice method called afterGetMessage() that runs after SimpleService.getMessage() and logs the message "Method getMessage() finished".
Spring Boot
Need a hint?

Use the pointcut expression execution(* SimpleService.getMessage(..)) to target the method.

3
Add @AfterReturning advice to log the returned value
In the LoggingAspect class, add an @AfterReturning advice method called afterReturningGetMessage() that runs after SimpleService.getMessage() returns. Capture the returned string in a parameter called result and log "Returned message: " followed by the result.
Spring Boot
Need a hint?

Use @AfterReturning with pointcut and returning attributes to capture the returned value.

4
Complete the Spring Boot application setup
Add the @SpringBootApplication annotation to a class called Application with a main method that runs the Spring application using SpringApplication.run(Application.class, args).
Spring Boot
Need a hint?

Use @SpringBootApplication and a main method to start the app.