Q1. What is Aspect-Oriented Programming (AOP)?
AOP is a programming paradigm that aims to increase modularity by allowing the separation of cross-cutting concerns. Cross-cutting concerns are aspects that affect multiple modules, such as logging, security, or transaction management. AOP allows you to define these aspects separately and then apply them declaratively.
Q2. What are the key concepts in Spring AOP?
Key concepts: Aspect (module encapsulating a concern), Joinpoint (point during execution, e.g., method call), Advice (action taken at a joinpoint), Pointcut (expression matching joinpoints), Introduction (adding new methods/fields), Target object (object being advised), Proxy (object created by AOP framework), Weaving (linking aspects with objects).
Q3. What types of advice are there in Spring AOP?
Advice types: Before (runs before method execution), After (after, regardless of outcome), After returning (after successful return), After throwing (after exception), Around (surrounds method invocation, most powerful). Each can be implemented using annotations like @Before, @After, etc.
Q4. How does Spring AOP differ from AspectJ?
Spring AOP is proxy-based and only supports method-level joinpoints, while AspectJ supports field-level and constructor joinpoints as well, and can weave at compile time or load time. Spring AOP is simpler and integrated with Spring, but AspectJ offers more power. Spring can also integrate with AspectJ for advanced scenarios.
Q5. You are Building a banking application. Currently, every method in AccountService, LoanService, and PaymentService contains duplicate code for logging and transaction management. Your manager asks you to centralize this logic so that
- Every method call is logged (before execution).
- Every method runs inside a database transaction.
How would you solve this using Spring AOP ? In your answer, identify the cross-cutting concerns and name the AOP key terms that apply.
Cross-cutting concerns: Logging and transaction management — these affect multiple modules and should be separated from business logic.
Solution using Spring AOP:
1. Aspect – Create an @Aspect class (e.g., BankingAspect) that contains the reusable code for logging and transaction handling.
2. Advice – Use @Before advice for logging (runs before method execution) and @Around advice for transaction management (surrounds method invocation).
3. Joinpoint – Each method execution in AccountService, LoanService, and PaymentService is a joinpoint where advice can be applied.
4. Pointcut – Write a pointcut expression like execution(* com.example.banking.*.*(..)) to match all methods in those service classes.
5. Weaving – At runtime, Spring weaves (links) the aspect with your business code using proxies, so your service classes remain clean.
This approach keeps business logic free from repetitive code, making it easier to maintain and modify later.
