Spring AOP
In a real application, your code has two types of logic:
1. Business Logic
- Payment processing
- Order creation
- Account transfer
2. Cross-Cutting Concerns
- Logging
- Security
- Transactions
- Monitoring
Without AOP
public void pay() {
log.info("Start");
securityCheck();
// business logic
log.info("End");
}
Problems:
- Same logging/security everywhere
- Code duplication
- Hard to maintain
- If logging logic changes β update 100 places
What AOP Does
@Service
class PaymentService {
public void pay() {
// Only business logic
}
}
@Aspect
@Component
class LoggingAspect {
@Before("execution(* com.app.service.*.*(..))")
public void log() {
System.out.println("Logging...");
}
}
AOP says:
Keep your business logic clean, and move common logic (logging, security, etc.) outside
π Business code remains clean
π Common logic is applied externally
So instead of writing logging everywhere, you define it once, and Spring applies it automatically where needed
Core Concepts
Aspect
A class that contains cross-cutting logic.
@Aspect
@Component
class LoggingAspect {}
Advice
The actual logic that runs.
@Before("execution(...)")
public void log() {
System.out.println("Logging...");
}
Join Point
A point where AOP can be applied.
π In Spring: only method execution
Pointcut
Defines where AOP should apply.
execution(* com.app.service.*.*(..))
Target Object
The actual business class.
@Service
class PaymentService {}
Proxy
Spring creates a proxy instead of calling the object directly.
Client β Proxy β Actual Method
Internal Flow
- Spring starts
- Detects @Aspect
- Creates proxy for beans
- Intercepts method calls
- Executes advice
- Calls actual method
Flow:
Client β Proxy β Advice β Target Method
Why AOP is Powerful
- Clean code
- No duplication
- Centralized logic
- Easy maintenance
Common Mistakes
- Ignoring proxy behavior
- Wrong pointcut expressions
- Self-invocation issue
AOP = Proxy + Interception + External Logic
Summary
- Separates cross-cutting concerns
- Uses proxy mechanism
- Works on Spring beans
- Improves maintainability