The @Aspect annotation marks a class as an aspect, which helps add extra behavior to your code without changing its core logic.
@Aspect annotation in Spring Boot
@Aspect
public class MyAspect {
// advice methods here
}@Aspect on a class to tell Spring it contains advice (extra code to run).@Before, @After, or @Around annotations to define when the extra code runs.com.example.service package runs.@Aspect public class LoggingAspect { @Before("execution(* com.example.service.*.*(..))") public void logBefore() { System.out.println("Method is about to run"); } }
com.example package takes to run.@Aspect public class TimingAspect { @Around("execution(* com.example..*(..))") public Object measureTime(org.aspectj.lang.ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); Object result = joinPoint.proceed(); long end = System.currentTimeMillis(); System.out.println("Execution took " + (end - start) + " ms"); return result; } }
This example shows a simple aspect that prints a message before the sayHello method runs in MyService. When you run the app and call sayHello, you see the aspect's message first, then the service's message.
package com.example.demo; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; import org.springframework.stereotype.Component; @Aspect @Component public class SimpleLoggingAspect { @Before("execution(* com.example.demo.MyService.sayHello(..))") public void beforeSayHello() { System.out.println("About to call sayHello method"); } } // Service class package com.example.demo; import org.springframework.stereotype.Service; @Service public class MyService { public void sayHello() { System.out.println("Hello from MyService!"); } } // Main application package com.example.demo; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; @SpringBootApplication public class DemoApplication { public static void main(String[] args) { ApplicationContext context = SpringApplication.run(DemoApplication.class, args); MyService service = context.getBean(MyService.class); service.sayHello(); } }
Remember to add @Component to your aspect class so Spring can find it.
Use pointcut expressions like execution(* package.Class.method(..)) to select where advice runs.
Aspects help keep your code clean by separating extra tasks like logging or security.
@Aspect marks a class as an aspect to add extra behavior.
Use it with advice annotations like @Before to run code at specific times.
It helps keep your main code simple and clean by handling cross-cutting concerns separately.
Practice
@Aspect annotation in Spring Boot?Solution
Step 1: Understand the role of @Aspect
The@Aspectannotation marks a class as an aspect, which means it can add extra behavior to other parts of the program without changing their code.Step 2: Differentiate from other annotations
Other options like REST controllers, database configuration, or scheduling are unrelated to@Aspect.Final Answer:
To mark a class as an aspect that can add extra behavior to other parts of the program -> Option DQuick Check:
@Aspect = marks aspect class [OK]
- Confusing @Aspect with @Controller
- Thinking @Aspect manages database or scheduling
- Assuming @Aspect runs HTTP endpoints
Solution
Step 1: Check correct annotation placement
The@Aspectannotation must be placed before the class declaration, like@Aspect public class MyAspect {}.Step 2: Identify invalid syntax
Options A, B, and D place@Aspectincorrectly or misuse syntax, causing errors.Final Answer:
@Aspect public class MyAspect {} -> Option AQuick Check:
@Aspect before class name = correct syntax [OK]
- Placing @Aspect after class name
- Using @Aspect on methods instead of classes
- Incorrect parentheses or missing class keyword
someMethod() is called?@Aspect
public class LoggingAspect {
@Before("execution(* someMethod())")
public void logBefore() {
System.out.println("Before method");
}
}Solution
Step 1: Understand @Before advice
The@Beforeannotation runs thelogBefore()method beforesomeMethod()executes, printing "Before method".Step 2: Confirm no errors or other outputs
There is no@Afteradvice or errors, so only "Before method" prints.Final Answer:
Before method -> Option CQuick Check:
@Before runs before target method [OK]
- Confusing @Before with @After
- Expecting no output if unaware of advice
- Assuming syntax errors without checking code
@Aspect
public class MyAspect {
@Before("execution(* someMethod())")
public void logBefore() {
System.out.println("Before method");
}
public void someMethod() {
System.out.println("Inside someMethod");
}
}Solution
Step 1: Check aspect registration
In Spring Boot, an aspect class must be a Spring bean to work. It needs@Componentor manual bean registration.Step 2: Validate other code parts
The pointcut expression and advice method are correct. HavingsomeMethod()inside the aspect is allowed but unusual.Final Answer:
The aspect class must be annotated with @Component or registered as a bean -> Option BQuick Check:
Aspect needs bean registration [OK]
- Ignoring @Component or bean registration
- Thinking advice methods must return values
- Assuming pointcut syntax is wrong without checking
@Aspect. Which approach correctly applies this?Solution
Step 1: Understand timing with @Around advice
@Around advice can run code before and after the target method, allowing precise measurement of execution time.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.Final Answer:
Use @Around advice with a pointcut matching all methods in the service class and measure time before and after proceeding -> Option AQuick Check:
@Around advice best for timing [OK]
- Using separate @Before and @After for timing
- Mixing logging code inside business methods
- Logging only on exceptions with @AfterThrowing
Ready to prove it?
Pass the test and this pattern moves unknown
