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