曹耘豪的博客

Spring之IoC

  1. Ioc(控制反转)原理
  2. 源码分析(自底向上)
    1. DefaultSingletonBeanRegistry
    2. FactoryBeanRegistrySupport
    3. AbstractBeanFactory
  3. Bean的三层缓存
  4. BeanDefinition
    1. 获取和构建

Ioc(控制反转)原理

工厂方法+反射

Spring通过IoC容器加载外部资源

DI:在系统运行过程中,动态的向某个对象提供它所需的对象

源码分析(自底向上)

DefaultSingletonBeanRegistry

singletonObjects,只有2个方法可以向其增加

earlySingletonObjects,只有1个方法可以向其增加,代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private final Map<String, Object> singletonObjects = new ConcurrentHashMap<>(256);
private final Map<String, Object> earlySingletonObjects = new ConcurrentHashMap<>(16);

@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
// Quick check for existing instance without full singleton lock
Object singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
// Consistent creation of early reference within full singleton lock
singletonObject = this.singletonObjects.get(beanName);
if (singletonObject == null) {
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null) {
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject); //【新创建的bean会先放到early里】
this.singletonFactories.remove(beanName);
}
}
}
}
}
}
return singletonObject;
}

FactoryBeanRegistrySupport

核心方法getObjectFromFactoryBean,由FactoryBean创建的Bean单独放个缓存

1
2
3
Map<String, Object> factoryBeanObjectCache = new ConcurrentHashMap<>(16);

Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess)

AbstractBeanFactory

Bean的三层缓存

主要解决循环依赖

BeanDefinition

获取和构建

主逻辑ClassPathBeanDefinitionScanner#doScan

ClassPathScanningCandidateComponentProvider#scanCandidateComponents

ClassPathBeanDefinitionScanner#postProcessBeanDefinition

AnnotationConfigUtils#processCommonDefinitionAnnotations(AnnotatedBeanDefinition, AnnotatedTypeMetadata)

最后注册到BeanDefinitionRegistry

   / 
  ,