Spring源码窥探之:单实例Bean的创建过程
finishBeanFactoryInitialization(beanFactory);初始化剩下的所有的单实例(非懒加载)Bean(Instantiate all remaining (non-lazy-init) singletons.)
1. beanFactory.preInstantiateSingletons();初始化剩下的所有的单实例(非懒加载)Bean
1) 首先获取所有BeanDefinition的名字List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
2) 根据名字获取Bean的定义信息RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
3) 再依次判断RootBeanDefinition不是抽象的,是单例的,不是懒加载的
1> 判断是不是工厂Bean,isFactoryBean(beanName),如果是的话,利用工厂来创建对象
2> 如果不是,就用getBean(beanName);来创建对象.
0. getBean(beanName)
1. doGetBean(name, null, null, false);
2. 先从缓存中获取单实例Bean,如果能获取到说明这个Bean创建过(所有创建过的单实例Bean都会被缓存起来)
Object sharedInstance = getSingleton(beanName);
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
3. 缓存中没有的话,就来创建对象.
4. 标记当前Bean已被创建
5. 获取Bean的定义信息
6. 获取当前Bean依赖的其它Bean(dependsOn),如果有按照getBean()把依赖的Bean先创建出来。
7. 启动单实例Bean的创建流程
1)createBean(beanName,mbd,args)
2)Object bean = resolveBeforeInstantiation(beanName, mbdToUse);让BeanPostProcessor先拦截返回代理对象
InstantiationAwareBeanPostProcessor提前执行:
先触发InstantiationAwareBeanPostProcessor接口中的postProcessBeforeInstantiation(beanClass, beanName);
如果有返回值,那么再触发InstantiationAwareBeanPostProcessor中的postProcessAfterInitialization(result, beanName);
3)如果InstantiationAwareBeanPostProcessor没有返回代理对象
4)Object beanInstance = doCreateBean(beanName, mbdToUse, args);创建Bean
1. 【创建Bean的实例】instanceWrapper = createBeanInstance(beanName, mbd, args);创建Bean
利用工厂方法或者构造器来创建Bean的实例
2. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
调用MergedBeanDefinitionPostProcessor的bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);