Spring容器入门级理解(Spring IOC Containers)

Spring容器入门级理解(Spring IOC Containers)

如何查官网文档

时隔很久,我又从第一页开始看《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类中
SpringContext
获取到的是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背后做了大量的工作,我也只是选取了一部分,剩下的还有待各位看官和我去慢慢理解。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值