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