spring版本:5.1.9(其它5.0及以上版本代码主线都区别不大)
辅助demo代码地址(在demo9中):
https://gitee.com/lelesccode/spring-sample-demo.git
spring的源码的知识比喻:
1.什么是BeanPostProcessor?
BeanPostProcessor通俗解释:后置处理器(增强对象)
用玩网游举个例子: 玩家人物(要被创建对象) /BeanPostProcessor(相当于主线任务或副本任务),玩家每过一个副本或 一个主线都给奖励你一个技能或武器道具.这样玩家的人物角色就得到了增强.
2.AOP原码解读:
1.EnableAspectJAutoProxy注解用意(spring boot做过封装不需要写):
主要作用是调用此方法org.springframework.aop.config.AopConfigUtils#registerOrEscalateApcAsRequired把ID为"org.springframework.aop.config.internalAutoProxyCreator"类型为:"AnnotationAwareAspectJAutoProxyCreator"注册到BeanDefinitionMap中,方法后面初始化bean:
3.在哪里对业务bean生成aop代理对象:
此代代码:org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean(java.lang.String, java.lang.Object, org.springframework.beans.factory.support.RootBeanDefinition)
获取切面通知方法org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#wrapIfNecessary为后面生成代理对象做准备(注意此处返回的通知切面方法为倒序,调用时有说明):
最终生位置代码:org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#createProxy
4.调用被代码对象的方法
public class SampleTest {
@Test
public void test01(){
AnnotationConfigApplicationContext app = new AnnotationConfigApplicationContext(SampleConfig.class);
Bike bean = app.getBean(Bike.class);
//调用被代理的目标方法
bean.div(10,4);
}
}
当前说cglib代理的对象(jdk的也基本一样):org.springframework.aop.framework.CglibAopProxy.DynamicAdvisedInterceptor#intercept