AOP (Aspect-Oriented Programming) is a programming paradigm that allows you to separate cross-cutting concerns (like logging, security, transactions) from your business logic, especially useful in Spring Framework.
What is a Cross-Cutting Concern?
A concern that affects multiple parts of your application:
-
Logging
-
Security
-
Transaction Management
-
Exception Handling
-
Caching
๐ฏ Why AOP?
Instead of writing the same logging or security code in every method, AOP lets you define that logic once and apply it transparently across the application.
✅ AOP Terminology
Term | Meaning |
---|---|
Aspect | A class that contains cross-cutting logic |
Join Point | A point during execution (e.g., method call) where an aspect can be applied |
Advice | Action taken by an aspect (before, after, around method execution) |
Pointcut | Expression that matches join points (e.g., all @Service methods) |
Weaving | Linking aspects with other application types at runtime or compile time |
๐ 1. Maven Dependency (Optional)
If you're using Spring Boot Starter, AOP support is already included. If not:
๐งฑ 2. Enable AOP in Main Class
๐งฉ 3. Create a Service Class (Business Logic)
๐ฏ 4. Create an Aspect Class
๐งช 5. Calling the Service
✅ Output on Request /api/greet?name=John
๐ Summary
Feature Description @Aspect Declares a class as an Aspect @Before Runs before matched method @AfterReturning Runs after successful execution @AfterThrowing Runs after method throws an exception @Around Wraps method, giving full control (most powerful) Pointcut Pattern to match method execution
Feature | Description |
---|---|
@Aspect | Declares a class as an Aspect |
@Before | Runs before matched method |
@AfterReturning | Runs after successful execution |
@AfterThrowing | Runs after method throws an exception |
@Around | Wraps method, giving full control (most powerful) |
Pointcut | Pattern to match method execution |
No comments:
Post a Comment