流程图
核心接口
Spring 声明周期
Bean 加载流程
执行流程详解
- 加载 Bean 定义信息(xml 配置、注解、配置类);
- 解析 Bean 信息(BeanDefinitionReader 读取器 Bean 信息);
- 读取 Bean 定义信息,用 ConcurrentHashMap 存储(BeanDefinition 存放Bean 实例、作用域等);
- BeanFactoryPostProcessor 扩展接口(BeanDefinition 属性增强器,通过 PlaceholderConfigurerSupport解析占位符, 如 @Value(“${xxxx}”)替换);
- 通过反射来创建 Bean 对象信息;
- 初始化对象(在堆中开辟新的空间→属性都是默认值);
- 如果该方法依赖其它的接口(@Autowired),通过 DI 注入(填充属性 populateBean 方法);
- *aware接口实现(设置aware接口属性:BeanNameAware等等);
- 如果实现了 BeanPostProcessor 接口(增强器,可以对方法前置和后置进行扩展);
- 前置增强器(postProcessBeforeInitialization 方法);
- Bean 初始化[init-method];
- 后置增强器(postProcessAfterInitialization 方法);
- Bean基本使用;
- 销毁(DisposableBean);
获取 bean 调用流程方法
Bean完成对象初始化过程
org.springframework.context.annotation.AnnotationConfigApplicationContext
org.springframework.context.support.AbstractApplicationContext#refresh
org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization
org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
org.springframework.beans.factory.support.AbstractBeanFactory#getBean(java.lang.String)--→849
org.springframework.beans.factory.support.AbstractBeanFactory#createBean--→320
--------------------------------------------------------------------------------------
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean--→515
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance--→555
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean--→592
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean--→593
Bean生命周期处理器
1. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInstantiation →1144
2. org.springframework.beans.factory.config.SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors →1324
3. MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition →1094
4. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#getEarlyBeanReference →962
5. InstantiationAwareBeanPostProcessor 1452
6. org.springframework.beans.factory.config.InstantiationAwareBeanPostProcessor#postProcessProperties 1502
7. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization 1914
8. org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization 1940
Bean 创建对象有几种方法
- new
- 反射