1. 初始化ApplicationContext(初始化bean容器, bean容器实际上就是Application拥有的BeanFactory)
new ApplicationContext()的时候。
发生了下面的操作:
BeanDefinitionReader读取resource里面指定的bean的xml配置文件。 并且把所有的单例bean存放到
ApplicationContext的BeanFactory的singletonObjects(HashMap结构)字段里去。
ApplicationContext的BeanFactory的singletonObjects字段就把xml文件中配置的所有的单例bean都存放好了。
2. 用applicationContext获取bean
applicationContext.getBean(String beanName)
实际上是
Object bean = applicationContext.getBeanFactory.getBean(String beanName);
AbstractBeanFactory继承了DefaultSingletonBeanRegistry里面有一个ConcurrentHashMap类型的singletonObjects来存放所有的已经被注册了的单例bean
(key是beanName,value是bean对象)
/** Cache of singleton objects: bean name --> bean instance */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
BeanFactory.getBean(), 如果是单例的,会调用这个方法,从singletonObjects中获取到对应的bean.
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
}
singletonObject被返回。这就是获取到的bean