Spring AOP实现机制

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方法

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容