AOP (Aspect-Oriented Programming)
AOP (Aspect-Oriented Programming)
What is AOP (Aspect-Oriented Programming)?
AOP is a programming paradigm that allows you to separate cross-cutting concerns (like logging, security, transactions, etc.) from the core business logic.
What are cross-cutting concerns?
These are concerns (code) that affect multiple parts of the application but are not part of the main business logic.
Examples:
- Logging, Security checks
- Transaction management
- Performance monitoring
- Caching, Async
Why use AOP?
Without AOP:
You might repeat the same logging/security code in many methods.
Your business logic becomes messy and harder to maintain.
With AOP:
You write that cross-cutting logic once and apply it wherever needed—automatically.
Simple Example in Spring Boot
Step 1: Add Spring AOP dependency (if not using Spring Boot Starter)
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
Step 2: Create a Service
@Service
public class UserService {
public void createUser() {
System.out.println("User created.");
}
}
Step 3: Create an Aspect for Logging
@Aspect
@Component
public class LoggingAspect {
@Before("execution( com.example.demo.UserService.(..))")
public void logBefore() {
System.out.println("Logging BEFORE method call...");
}
@After("execution( com.example.demo.UserService.(..))")
public void logAfter() {
System.out.println("Logging AFTER method call...");
}
}
Explanation:
- @Aspect: Marks this class as an Aspect.
- @Before(...): Runs before any method in `UserService` is called.
- @After(...): Runs after the method execution.
- execution(...): A point-cut expression to match method calls.
Step 4: Run and See the Output
If you call: userService.createUser();
Output:
Logging BEFORE method call...
User created.
Logging AFTER method call...
Breakdown:
Cross-cutting concerns: Reusable logic like logging, transactions, security, etc.
Business logic: Your core application logic (e.g., creating users, placing orders).
The code we implement to handle these concerns is applied to our business logic through proxy objects in Spring. Proxy in Spring:
- Spring creates a proxy object around your bean (e.g., a service class).
- When you call a method, the proxy intercepts the call.
- It can run code before/after/around your business method (called advice).
- Then it proceeds to your original method.
Annotations like @Component, @Service, @Repository, @Controller are stereotype annotations to register beans in the Spring container.
Annotations like @Transactional, @Cacheable, @Async are AOP-powered annotations
How to Identify an AOP-Based Annotation: If an annotation adds behavior before, after, or around your method execution — it’s likely using AOP.
Comments
Post a Comment