如何查官网文档
时隔很久,我又从第一页开始看《Spring源码深度解析》这本书(你说得对,这本书我从来就没有看完过)。正在我陷入代码的漩涡之时,我问了自己一个问题:什么是Spring容器?
Tips:很多技术书很难啃完,建议读者可以选读,或者带着一个问题去读,读书的目的在于学习技能或者理解一项事务,而不是翻书。
带着这个问题,首选是求助度娘,上下求索,那些博客着实把我看晕了,因为各有说法,相信这也是很多人查找资料的疑惑,这个时候权威的解释从哪儿找?当然是一手资源的官网。
https://spring.io/
1 Step
2 Step
3 Step
4 Step
权威描写如下
The org.springframework.context.ApplicationContext interface represents the Spring IoC container and is responsible for instantiating, configuring, and assembling the beans.
建议想了解的读者,官网通读一下这部分内容。
Bean的获取流程
使用ApplicationContext的时候,我们会使用getBean方法
@Override
public Object getBean(String name) throws BeansException {
assertBeanFactoryActive();
return getBeanFactory().getBean(name);
}
这个方法在AbstractApplicationContext类中
获取到的是ConfigurableListableBeanFactory
@Override
public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;
AbstractBeanFactory中getBean
@Override
public Object getBean(String name) throws BeansException {
return doGetBean(name, null, null, false);
}
由于doGetBean源码中又较多其他逻辑,核心是调用了DefaultSingletonBeanRegistry getSingleton方法
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
//关键代码
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
重点对象来了,singletonObjects
/** Cache of singleton objects: bean name to bean instance. */
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
一句话理解
看到最后,你自己是不是已经有了答案,这不就是一个Map吗?
当然Spring背后做了大量的工作,我也只是选取了一部分,剩下的还有待各位看官和我去慢慢理解。