0
0
Spring Bootframework~30 mins

Pointcut expressions in Spring Boot - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Pointcut Expressions in Spring Boot
📖 Scenario: You are building a Spring Boot application that needs to log method calls in a service class. You want to use Aspect-Oriented Programming (AOP) to intercept method executions using pointcut expressions.
🎯 Goal: Create a Spring Boot aspect that uses pointcut expressions to match all methods in the CalculatorService class and logs a message before each method runs.
📋 What You'll Learn
Create a CalculatorService class with two methods: add and subtract.
Create an aspect class called LoggingAspect.
Define a pointcut expression that matches all methods in CalculatorService.
Add a @Before advice that logs a message before any matched method executes.
💡 Why This Matters
🌍 Real World
Logging method calls is common in real applications to track behavior and debug issues without changing business logic.
💼 Career
Understanding pointcut expressions and AOP is important for backend developers working with Spring Boot to implement cross-cutting concerns like logging, security, and transactions.
Progress0 / 4 steps
1
Create CalculatorService with methods
Create a class called CalculatorService with two public methods: add that takes two integers and returns their sum, and subtract that takes two integers and returns their difference.
Spring Boot
Need a hint?

Define a public class named CalculatorService. Add two public methods named add and subtract with two integer parameters each. Return the sum and difference respectively.

2
Create LoggingAspect class with @Aspect annotation
Create a class called LoggingAspect and annotate it with @Aspect and @Component to make it a Spring-managed aspect.
Spring Boot
Need a hint?

Import @Aspect and @Component. Annotate the class LoggingAspect with both annotations.

3
Define pointcut expression for CalculatorService methods
Inside LoggingAspect, define a pointcut method called allCalculatorMethods annotated with @Pointcut. Use the expression execution(* CalculatorService.*(..)) to match all methods in CalculatorService.
Spring Boot
Need a hint?

Use @Pointcut annotation with the expression execution(* CalculatorService.*(..)). Define an empty method named allCalculatorMethods to hold this pointcut.

4
Add @Before advice to log before method execution
Add a @Before advice method called logBeforeMethod in LoggingAspect that uses the pointcut allCalculatorMethods(). Inside the method, add a simple log statement using System.out.println that prints "Method is about to execute".
Spring Boot
Need a hint?

Use @Before annotation with the pointcut method allCalculatorMethods(). Define a method logBeforeMethod that prints the log message.