简单介绍
Spring在IoC容器初始化完毕,会把非lazy-init的bean初始化,方法入口是 org.springframework.context.support.AbstractApplicationContext#finishBeanFactoryInitialization()方法里的beanFactory.preInstantiateSingletons(); 其中的beanFactory默认是DefaultListableBeanFactory的一个实例. 这行代码的注释是 Instantiate all remaining (non-lazy-init) singletons. 初始化其他非懒加载的单例beans.
开始
我们以其中一个bean为例.这里为了简化问题,我们先忽略初始化的时候一些和普通bean无关的分支,专注于一个普通的bean初始化. 每一个普通的bean都会执行getBean(String name)方法,这个方法其实就是我们最常用的context.getBean(name)方法. 现在就是单例bean的获取过程了. 首先执行 org.springframework.beans.factory.support.AbstractBeanFactory#doGetBean
/** Cache of singleton factories: bean name to ObjectFactory. */ private final Map<String, ObjectFactory> singletonFactories = new HashMap<>(16);
/** Cache of early singleton objects: bean name to bean instance. */ private final Map<String, Object> earlySingletonObjects = new HashMap<>(16);
/** Names of beans that are currently in creation. */ private final Set singletonsCurrentlyInCreation = Collections.newSetFromMap(new ConcurrentHashMap<>(16));
org.springframework.context.annotation.internalConfigurationAnnotationProcessor org.springframework.context.annotation.internalAutowiredAnnotationProcessor org.springframework.context.event.internalEventListenerProcessor org.springframework.context.event.internalEventListenerFactory sampleServiceImpl sampleBeanPostProcessor
RootBeanDefinition
[li.dongpo.tc.service.SampleServiceImpl]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null; defined in class path resource [spring.xml]
GenericBeanDefinition RootBeanDefinition DefaultSingletonBeanRegistry InstantiationAwareBeanPostProcessor
CglibSubclassingInstantiationStrategy
overriddenDefaultEditors
alreadyCreated
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences && isSingletonCurrentlyInCreation(beanName));
private final Map<String, Object> singletonObjects = 一级缓存
private final Map<String, ObjectFactory> singletonFactories = 三级
private final Map<String, Object> earlySingletonObjects = 二级
AutowiredAnnotationBeanPostProcessor
NamespaceHandler BeanPostProcessor BeanDefinitionParser