tips:1)引入起步依赖
沿用ioC的工厂
tips:Spring AOP:
十个人有九 个人弄不懂的关系
AspectJ编译期和类加载时进行织入、Spring AOP利用的是运行时织入
容器启动2、代理对象到底长什么样?
接下来,我们会找到$Proxy生成的始末3、我的接口是怎么被A0P管理上的 ?
tips:1.4 代理对象是怎么生成的
当然是execution声明,改成 SlaverImpl.aaaa*(..) , 再来看getBean的对象,不再是proxy
断点一下……
1、AOP其实就是用的动态代理模式,创建代理目标:通过源头找代理对象是如何生成的
2、AOP织入源头在哪里
开始之前,我们先必须搞懂一件事情:1)从源头找代理对象生成
那就是:代理模式
设计模式【静态代理】 【动态代理】 回顾 (见第2小节)
tips:从后置处理器开始找到后置处理器
为什么要从后置处理器入手?
很容易理解,没初始化好没法用,等你初始化好了功能齐备了,我再下手,代替你
此处最好使用断点表达式,否则要循环很多次断点表达式:
因为在refresh方法中的invokeBeanFactoryPostProcessors方法也会调用到这个地方
tips:AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization
在BeanPostProcessor循环中,观察AnnotationAwareAspectJAutoProxyCreator
这货就是切面的后置处理器
如上所见2)进入后置处理器
也就是说AOP模块是通过实现BeanPostProcessor集成进来的
tips:AbstractAutoProxyCreator#postProcessAfterInitialization
aop这是spring内置的一个后置处理器,生效在postProcessAfterInitialization方法
tips:这是我们一开始的结果,下面我们来再debug到work方法时,点击debug into试试,发现调到哪里去了???
前面创建完成了代理对象,下面我们看下它调用的时候,是不是走了代理
注意:上图的颜色区分注意,我们的链条如下:
黑色:表示正向调用,invoke的时候,在前或后执行自己的切面逻辑,然后推动责任链往下走
红色:表示当前切面任务触发的点
备注:ExposeInvocationInterceptor 是spring帮我们加上做上下文传递的,本图不涉及(它在最前面)
调试技巧:
从 ReflectiveMethodInvocation.invoke() 开始,对照上面的责任链嵌套调用图
每次通过debug into 进行查看,每到一环,注意对照图上的节点,看到那个invocation了!
总结:(记住两点)有没有其他的方式可以减少代码的维护,那就是动态代理?
1、只需要知道静态代理是在运行前代理类就已经被织入进去了
2、大规模使用静态代理难以维护(增加方法)
Proxy1)代理父类Proxy回顾
InvocationHandler
tips:重要
重点关注newProxyInstance
这三个参数非常重要
Spring Aop也是使用这个机制
1、目标对象(委托类)通过jdk的Proxy生成了代理对象、InvocationHandler的核心方法
2、客户端访问代理对象,代理对象通过调用于处理器接口反射调用了目标对象方法
tips接口
代理对象不需要实现接口(业务),但是目标对象一定要实现接口,否则不能用动态代理
tips:参考资料:https://www.baiyp.ren/JAVA动态代理源码分析.html
涉及JDK字节码,不在spring的源码范围内,感兴趣的同学自己了解一下
核心代码参看以上注释断点查看slaver.work()
本文由传智教育博学谷教研团队发布。
如果本文对您有帮助,欢迎关注和点赞;如果您有任何建议也可留言评论或私信,您的支持是我坚持创作的动力。
转载请注明出处!
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) | Powered by Discuz! X3.4 |