1,AOP環境配置
1)引入aop的jar包
compile 'org.springframework:spring-aop:x.x.x.RELEASE' 版本號同項目中的一致即可
2)aop開啟,@Aspect
proxyTargetClass:默認false表示使用jdk動態代理,如果為true或者目標類沒有聲明接口,則使用cglib動態代理。
<aop:aspectj-autoproxy proxy-target-class="false"/>
@EnableAspectJAutoProxy(proxyTargetClass = false)
2,AOP概念
1)連接點(Joinpoint) :
runtime joinpoint運行時的連接點。如方法調用MethodInvocation、ConstructorInvocation以及異常處理塊等。
image.png
image.png
2)切點(Pointcut):連接點的描述定義,通過切點定位哪些連接點(縮小范圍)。
如AnnotationMatchingPointcut(注解匹配的切點)、NameMatchMethodPointcut(方法名匹配的切點)等。
image.png
3)通知(Advice)在連接點上執行的動作
BeforeAdvice:前置通知。如MethodBeforeAdvice,在方法被調用前通知。
AfterAdvice:后置通知。如AfterReturningAdvice,在方法返回后通知。
Around :環繞通知。執行前后
4)目標對象(Target Object)
即被通知的對象,代理對象
5)切面Aspect :通知+切入點=切面。
image.png
3,@EnableAspectJAutoProxy底層實現
1)開啟AspectJ支持
Enables support for handling components marked with AspectJ's @Aspect annotation
導入AspectJAutoProxyRegistrar:
image.png
注冊bean
image.png
image.png
2)AnnotationAwareAspectJAutoProxyCreator類圖
image.png
3)AbstractAutoProxyCreator
BeanPostProcessor:允許自定義修改創建bean的實例。e.g. checking for marker interfaces or wrapping them with proxies.
image.png
AbstractAutoProxyCreator實現BeanPostProcessor:每次Bean的裝配時,都會檢查,如果符合條件則獲取切面信息,并創建代理對象
image.png
image.png
4)cglib和jdk動態代理的區別
JDK動態代理:基于接口,只能對實現了接口的類生成代理。
CGLIB動態代理:基于繼承,對指定類生成子類實現代理。無法代理final方法