Spring Notes (3) - AOP
AOP: Aspect Oriented Programming
Implemented using dynamic proxy.
Traditional Methods
- Interface-based dynamic proxy:
Proxy.newProxyInstance - Subclass-based dynamic proxy:
Enhancer.create
Terminology
- JoinPoint: All methods in the proxied class.
- Pointcut: The methods that are enhanced/advised.
- Advice/Enhancement: What to do after intercepting JoinPoint.
- Before Advice: Before transaction
- After Advice: After transaction
AOP Implementation in Spring
<aop:config>
<aop:aspect id="logAspect" ref="loggingAspect">
<aop:before method="beforeLog" pointcut="execution(* xyz.aiinirii..*.*(..))"/>
</aop:aspect>
</aop:config>
Using Annotations
@Aspect
@Component
public class LoggingAspect {
@Before("execution(* xyz.aiinirii..*.*(..))")
public void beforeLog() {
System.out.println("Before method execution");
}
@AfterReturning("execution(* xyz.aiinirii..*.*(..))")
public void afterLog() {
System.out.println("After method execution");
}
@AfterThrowing("execution(* xyz.aiinirii..*.*(..))")
public void exceptionLog() {
System.out.println("Exception occurred");
}
}
Summary
AOP helps separate cross-cutting concerns (like logging, security, transactions) from business logic.