AOP lets you keep code for things like logging, security checks, or transactions separate from your main business code. This keeps your code clean and easier to change.
public class UserService { public void createUser(String name) { System.out.println("Creating user: " + name); } } @Aspect @Component public class LoggingAspect { @Before("execution(* UserService.createUser(..))") public void logBefore() { System.out.println("Starting user creation"); } }
The @Before advice runs just before the createUser method, so the log message appears first, then the method's print statement.
@Before("execution(* MyService.process(..))") public void beforeAdvice() { System.out.println("Before processing"); } @After("execution(* MyService.process(..))") public void afterAdvice() { System.out.println("After processing"); } public void process() { System.out.println("Processing"); }
The @Before advice runs first, then the method body, then the @After advice.
Option B matches all methods in classes inside com.example.service package and its subpackages using standard syntax (package..*). Option B matches methods in classes inside subpackages only, but is less common. Options C and D are invalid syntax.
For AOP to work, the aspect must be a Spring bean, usually annotated with @Component and scanned. Without this, the advice won't run.