Concept Flow - @Before advice
Method call starts
@Before advice runs
Original method executes
Method call ends
When a method is called, the @Before advice runs first, then the original method runs, then the call ends.
import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Before; @Aspect public class MyAspect { @Before("execution(* MyService.doWork(..))") public void beforeAdvice() { System.out.println("Before advice runs"); } }
| Step | Action | Output | Next Step |
|---|---|---|---|
| 1 | Call MyService.doWork() | No output yet | Run @Before advice |
| 2 | Run @Before advice | Prints: Before advice runs | Run original method |
| 3 | Run original method doWork() | Original method output (if any) | Method call ends |
| 4 | Method call ends | No further action | Exit |
| Variable | Start | After Step 2 | After Step 3 | Final |
|---|---|---|---|---|
| methodCall | not started | beforeAdvice executed | original method executed | completed |
@Before advice runs before the target method.
It cannot change the method's return value.
Use @Before("pointcut") to specify where it applies.
It is useful for logging or setup before method runs.
Execution order: @Before advice -> original method -> end.@Before advice in Spring AOP?@Before advice method in Spring AOP?service.process() is called?@Aspect
@Component
public class LoggingAspect {
@Before("execution(* com.example.service.Service.process(..))")
public void beforeProcess() {
System.out.println("Before process");
}
}
@Service
public class Service {
public void process() {
System.out.println("Processing");
}
}@Before advice definition:@Before("execution(* com.example..*(..))")
public void beforeMethod() {
System.out.println("Before method");
}com.example.repository package is called, but only for methods starting with save. Which @Before pointcut expression correctly matches this?Pass the test and this pattern moves unknown