AOP - Aspect Oriented Programming
In enterprise applications, developers often need to implement cross-cutting concerns such as logging, auditing, security, performance monitoring, and transaction management. Embedding this logic inside every business method leads to duplicate code, poor maintainability, and increased development effort.
Aspect-Oriented Programming (AOP) solves this problem by separating cross-cutting concerns from the core business logic. These concerns are implemented as Aspects, allowing centralized management without modifying the business code.
- Application Logging
- Auditing
- Performance Monitoring
- Security Checks
- Exception Handling
- Transaction Management (@Transactional)
AOP Architecture
Client Request
│
▼
Before Advice
│
▼
Business Method
│
┌────────────┴────────────┐
│ │
▼ ▼
After Returning After Throwing
│ │
└────────────┬────────────┘
▼
After Advice
AOP Terminologies
1. Aspect
An Aspect is a class that contains one or more Pointcuts and Advices. It represents a cross-cutting concern.
@Component
@Aspect
public class LoggingAspect {
}
2. Pointcut
A Pointcut defines where an Advice should execute. It identifies one or more Join Points using AspectJ expressions.
Common Pointcut Expressions
| Expression | Description |
|---|---|
execution() |
Matches specific method executions. |
within() |
Matches all methods inside a class or package. |
this() |
Matches methods executed on objects implementing a specific type. |
Examples
// Match every method inside controller package
@Pointcut(
"execution(* com.alpha.spring.security.user.controller.*.*(..))"
)
public void controllerMethods(){ }
// Match every method inside authentication package
@Pointcut(
"within(com.alpha.spring.security.authentication.*)"
)
public void authenticationPackage(){ }
// Match methods executed on a specific implementation
@Pointcut(
"this(com.alpha.spring.security.user.service.UserDetailsServiceImpl)"
)
public void serviceImplementation(){ }
3. Advice
An Advice defines what action should be executed when a Pointcut is matched.
| Advice | Execution Time | Typical Usage |
|---|---|---|
| @Before | Before method execution | Validation, Logging |
| @AfterReturning | After successful completion | Audit, Logging |
| @AfterThrowing | After exception occurs | Error Logging |
| @After | Always executes | Cleanup |
| @Around | Before and After | Performance, Security |
4. Join Point
A Join Point is a specific point during program execution where an Aspect can be applied.
Typical Join Points include:
- Method Execution
- Constructor Execution
- Field Access
- Exception Handling
- Object Initialization
- Static Initialization
Examples
// Method execution
execution(* com.example.service.*.*(..))
// Constructor execution
execution(com.example.model.User.new(..))
// Read field
get(* com.example.model.User.name)
// Write field
set(* com.example.model.User.name)
// Exception handler
handler(Exception)
// Object initialization
initialization(* new(..))
// Static initialization
staticinitialization(com.example.model.User)
Logging Aspect Example
The following Aspect demonstrates how centralized logging can be implemented without modifying any controller methods.
@Component
@Aspect
@Slf4j
public class AuthenticationAspect {
@Pointcut(
"execution(* com.alpha.spring.security.user.controller.*.*(..))"
)
public void loggingPointCut(){}
@Before("loggingPointCut()")
public void before(JoinPoint joinPoint){
log.info(
"Before : {}",
joinPoint.getSignature()
);
}
@After("loggingPointCut()")
public void after(JoinPoint joinPoint){
log.info(
"After : {}",
joinPoint.getSignature()
);
}
@AfterReturning(
value="loggingPointCut()",
returning="users"
)
public void afterReturning(
JoinPoint joinPoint,
List users){
log.info(
"Returned : {}",
users
);
}
@AfterThrowing(
value="loggingPointCut()",
throwing="ex"
)
public void afterThrowing(
JoinPoint joinPoint,
Exception ex){
log.error(
"Exception : {}",
ex.getMessage()
);
}
@Around("loggingPointCut()")
public Object around(
ProceedingJoinPoint point)
throws Throwable{
long start = System.currentTimeMillis();
Object result = point.proceed();
long end = System.currentTimeMillis();
log.info(
"Execution Time : {} ms",
(end-start)
);
return result;
}
}
Custom Annotation Example
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface CustomAnnotation {
}
Using the custom annotation:
@Before(
"@annotation(com.alpha.spring.security.annotation.CustomAnnotation)"
)
public void annotatedMethod(){
log.info("Custom Annotation Executed");
}
Advantages of AOP
- Removes duplicate code
- Centralized logging
- Improves maintainability
- Cleaner business logic
- Reusable cross-cutting concerns
- Easy auditing and monitoring
- Supports declarative transaction management
Spring internally uses AOP for many important features, including:
- @Transactional
- @Cacheable
- @Async
- @Secured
- @PreAuthorize
- Method Validation
A common interview question is: "How does @Transactional work internally?" The answer is that Spring creates a proxy using AOP. The proxy starts a transaction before the method executes, commits it if the method completes successfully, or rolls it back if an exception occurs.
References
- https://www.youtube.com/watch?v=POa6ZZKq79E
- https://reflectoring.io/aop-spring/
Comments
Post a Comment