Aspect-Oriented Programing (AOP) Overview
According to the Spring tutorial by King God's Spring 07: "AOP Made Simple" (qq.com)
-
Understanding AOP
Aspect-Oriented Programming (AOP) refers to a programming paradigm that enables unified maintenance of program functionalities through pre-compilation and runtime dynamic proxies. AOP extends OOP principles and represents a crucial concept in Spring framework development. It functions as a functional prgoramming derivative model that isolates various components of business logic, thereby reducing coupling between different parts of an application, enhancing reusability, and improving overall development efficiency.
-
Practical Applications of AOP
-
Implementation via Spring API Interfaces
<!-- Configure AOP --> <aop:config> <!-- Define pointcut: expression specifies where to apply, execution(* com.wjj.service.UserServiceImpl.*(..)) --> <aop:pointcut id="pointcut" expression="execution(* com.wjj.service.UserServiceImpl.*(..))"/> <aop:advisor advice-ref="after" pointcut-ref="pointcut"/> <aop:advisor advice-ref="before" pointcut-ref="pointcut"/> </aop:config> -
Custom AOP Implementation
<bean id="diy" class="com.wjj.diy.DiyPointcut" /> <aop:config> <!-- Define custom aspect, reference to class --> <aop:aspect ref="diy"> <!-- Define pointcut --> <aop:pointcut id="pointcut" expression="execution(* com.wjj.diy.DiyPointcut.*(..))"/> <!-- Define advice --> <aop:before method="before" pointcut-ref="pointcut"/> <aop:after method="after" pointcut-ref="pointcut"/> </aop:aspect> </aop:config>
-
-
AOP Implementation Using Annotations
public class AnnotationPinot {
@Before("execution(* com.wjj.service.UserServiceImpl.*(..))")
public void before() {
System.out.println("Before============");
}
@After("execution(* com.wjj.service.UserServiceImpl.*(..))")
public void after() {
System.out.println("================After");
}
@Around("execution(* com.wjj.service.UserServiceImpl.*(..))")
public void around(ProceedingJoinPoint pjp) throws Throwable {
System.out.println("Before Around");
Object proceed = pjp.proceed();
System.out.println("After Around");
}
}
<!-- Enable auto-proxy support, default is JDK proxy (proxy-target-class="false"), use CGLIB (proxy-target-class="true") -->
<aop:aspectj-autoproxy proxy-target-class="false"/>
<!-- Alternative approach -->
<bean id="annotationPinot" class="com.wjj.diy.AnnotationPinot"/>