Bird
Raised Fist0
Spring Bootframework~10 mins

@Aspect annotation in Spring Boot - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - @Aspect annotation
Define Aspect Class
↓
Add @Aspect Annotation
↓
Define Pointcut Expression
↓
Define Advice Method (e.g., @Before)
↓
Spring AOP Proxy Created
↓
Target Method Called
↓
Advice Runs Before/After Target Method
↓
Target Method Executes
↓
Return to Caller
This flow shows how an @Aspect class is defined, advice methods are set, and how Spring AOP runs advice around target method calls.
Execution Sample
Spring Boot
import org.aspectj.lang.annotation.*;

@Aspect
public class LoggingAspect {
  @Before("execution(* com.example.service.*.*(..))")
  public void logBefore() {
    System.out.println("Method is about to run");
  }
}
Defines an aspect with a @Before advice that logs before any method in com.example.service package runs.
Execution Table
StepActionEvaluationResult
1Spring scans for @Aspect classesFinds LoggingAspectLoggingAspect registered as aspect
2Spring creates proxy for target beansTarget beans in com.example.serviceProxies wrap target beans
3Client calls target method serviceMethod()Matches pointcut expressionAdvice logBefore() triggered
4Advice logBefore() runsPrints messageOutput: 'Method is about to run'
5Target method serviceMethod() runsExecutes original logicTarget method completes
6Return to clientMethod call endsExecution finished
💡 Execution stops after target method completes and returns to caller
Variable Tracker
VariableStartAfter Step 3After Step 4After Step 5Final
LoggingAspect instancenullcreatedactiveactiveactive
Target method callnoneinvokedwaitingexecutingcompleted
Advice triggeredfalsetruetruefalsefalse
Key Moments - 3 Insights
Why does the advice run before the target method?
Because the @Before annotation tells Spring AOP to run the advice method before the matched target method, as shown in execution_table step 4.
How does Spring know which methods to apply the advice to?
Spring uses the pointcut expression in the @Before annotation to match method signatures, as seen in execution_table step 3.
Is the original target method replaced by the advice?
No, the advice runs around the target method but does not replace it; the target method still executes after advice, as shown in steps 5 and 6.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens at step 4?
AThe target method starts executing
BSpring scans for @Aspect classes
CThe advice method logBefore() runs and prints a message
DThe client receives the method result
💡 Hint
Check the 'Action' and 'Result' columns at step 4 in execution_table
At which step does the target method actually execute?
AStep 5
BStep 4
CStep 3
DStep 6
💡 Hint
Look for 'Target method runs' in the 'Action' column of execution_table
If the pointcut expression did not match any method, what would change in the execution_table?
AAdvice would still run before the target method
BAdvice would never run, target method runs normally
CSpring would not create any proxies
DThe target method would be replaced by advice
💡 Hint
Refer to step 3 where matching triggers advice; no match means no advice
Concept Snapshot
@Aspect annotation marks a class as an aspect.
Use pointcut expressions to select methods.
Advice methods (@Before, @After, etc.) run around target methods.
Spring creates proxies to apply advice.
Advice runs without replacing original methods.
Useful for logging, security, transactions.
Full Transcript
The @Aspect annotation in Spring Boot marks a class as an aspect that contains advice methods. Spring scans for these classes and creates proxies for target beans matching pointcut expressions. When a client calls a target method, Spring runs the advice method first if annotated with @Before, then executes the target method. This allows adding behavior like logging without changing the original code. The execution flow starts with scanning, proxy creation, method call, advice execution, target method execution, and finally returning to the caller. Variables like the aspect instance and advice trigger state change during execution. Common confusions include why advice runs before the method, how Spring matches methods, and that advice does not replace the target method. Visual quizzes reinforce understanding of each step.

Practice

(1/5)
1. What is the primary purpose of the @Aspect annotation in Spring Boot?
easy
A. To schedule tasks to run at fixed intervals
B. To define a REST controller for handling HTTP requests
C. To configure database connections automatically
D. To mark a class as an aspect that can add extra behavior to other parts of the program

Solution

  1. Step 1: Understand the role of @Aspect

    The @Aspect annotation marks a class as an aspect, which means it can add extra behavior to other parts of the program without changing their code.
  2. Step 2: Differentiate from other annotations

    Other options like REST controllers, database configuration, or scheduling are unrelated to @Aspect.
  3. Final Answer:

    To mark a class as an aspect that can add extra behavior to other parts of the program -> Option D
  4. Quick Check:

    @Aspect = marks aspect class [OK]
Hint: Remember: @Aspect marks classes for extra behavior [OK]
Common Mistakes:
  • Confusing @Aspect with @Controller
  • Thinking @Aspect manages database or scheduling
  • Assuming @Aspect runs HTTP endpoints
2. Which of the following is the correct way to declare an aspect class in Spring Boot?
easy
A. @Aspect public class MyAspect {}
B. public class MyAspect @Aspect {}
C. @Aspect() void MyAspect() {}
D. class MyAspect @Aspect public {}

Solution

  1. Step 1: Check correct annotation placement

    The @Aspect annotation must be placed before the class declaration, like @Aspect public class MyAspect {}.
  2. Step 2: Identify invalid syntax

    Options A, B, and D place @Aspect incorrectly or misuse syntax, causing errors.
  3. Final Answer:

    @Aspect public class MyAspect {} -> Option A
  4. Quick Check:

    @Aspect before class name = correct syntax [OK]
Hint: Put @Aspect right before the class keyword [OK]
Common Mistakes:
  • Placing @Aspect after class name
  • Using @Aspect on methods instead of classes
  • Incorrect parentheses or missing class keyword
3. Given this aspect code snippet, what will be printed when someMethod() is called?
@Aspect
public class LoggingAspect {
  @Before("execution(* someMethod())")
  public void logBefore() {
    System.out.println("Before method");
  }
}
medium
A. After method
B. No output
C. Before method
D. Compilation error

Solution

  1. Step 1: Understand @Before advice

    The @Before annotation runs the logBefore() method before someMethod() executes, printing "Before method".
  2. Step 2: Confirm no errors or other outputs

    There is no @After advice or errors, so only "Before method" prints.
  3. Final Answer:

    Before method -> Option C
  4. Quick Check:

    @Before runs before target method [OK]
Hint: @Before prints before method runs [OK]
Common Mistakes:
  • Confusing @Before with @After
  • Expecting no output if unaware of advice
  • Assuming syntax errors without checking code
4. Identify the error in this aspect code:
@Aspect
public class MyAspect {
  @Before("execution(* someMethod())")
  public void logBefore() {
    System.out.println("Before method");
  }

  public void someMethod() {
    System.out.println("Inside someMethod");
  }
}
medium
A. The pointcut expression is incorrect
B. The aspect class must be annotated with @Component or registered as a bean
C. The advice method logBefore() must return a value
D. The someMethod() cannot be inside the aspect class

Solution

  1. Step 1: Check aspect registration

    In Spring Boot, an aspect class must be a Spring bean to work. It needs @Component or manual bean registration.
  2. Step 2: Validate other code parts

    The pointcut expression and advice method are correct. Having someMethod() inside the aspect is allowed but unusual.
  3. Final Answer:

    The aspect class must be annotated with @Component or registered as a bean -> Option B
  4. Quick Check:

    Aspect needs bean registration [OK]
Hint: Aspect classes must be Spring beans to work [OK]
Common Mistakes:
  • Ignoring @Component or bean registration
  • Thinking advice methods must return values
  • Assuming pointcut syntax is wrong without checking
5. You want to log execution time of all methods in a service class using @Aspect. Which approach correctly applies this?
hard
A. Use @Around advice with a pointcut matching all methods in the service class and measure time before and after proceeding
B. Use @Before advice to start timer and @After advice to stop timer separately
C. Add logging code directly inside each service method instead of using @Aspect
D. Use @AfterThrowing advice to log execution time only when exceptions occur

Solution

  1. Step 1: Understand timing with @Around advice

    @Around advice can run code before and after the target method, allowing precise measurement of execution time.
  2. Step 2: Evaluate other options

    @Before and @After separately cannot measure total time easily; direct logging mixes concerns; @AfterThrowing only runs on exceptions, missing normal cases.
  3. Final Answer:

    Use @Around advice with a pointcut matching all methods in the service class and measure time before and after proceeding -> Option A
  4. Quick Check:

    @Around advice best for timing [OK]
Hint: Use @Around to wrap method and measure time [OK]
Common Mistakes:
  • Using separate @Before and @After for timing
  • Mixing logging code inside business methods
  • Logging only on exceptions with @AfterThrowing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard