Spring 源码之核心加载方法(12) 实例化对象

12.2 AbstractAutowireCapableBeanFactory#createBean

定位: org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBean(String, RootBeanDefinition, Object[])

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
@Override
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

if (logger.isTraceEnabled()) {
logger.trace("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;

// Make sure bean class is actually resolved at this point, and
// clone the bean definition in case of a dynamically resolved Class
// which cannot be stored in the shared merged bean definition.
// 锁定class,根据设置的class属性或者根据className来解析class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
// 进行条件筛选,重新赋值RootBeanDefinition,并设置BeanClass属性
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
// 重新创建一个RootBeanDefinition对象
mbdToUse = new RootBeanDefinition(mbd);
// 设置BeanClass属性值
mbdToUse.setBeanClass(resolvedClass);
}

// Prepare method overrides.
// 验证及准备覆盖的方法,lookup-method replace-method,
// 当需要创建的bean对象中包含了lookup-method和replace-method标签的时候,会产生覆盖操作
try {
// 验证以及准备覆盖的方法即Override方法
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
// 返回代理来代替真正的实例:--------------应用实例化前的前置处理器
// 给BeanPostProcessors一个机会来返回代理来替代真正的实例,应用实例化前的前置处理器
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}

try {
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
// A previously detected exception with proper bean creation context already,
// or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
throw ex;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
}
}

12.2.1 AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#resolveBeforeInstantiation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 如果beforeInstantiationResolved值为null或者true,那么表示尚未被处理,进行后续的处理
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
// 确认beanClass确实在此处进行处理
// 判断当前mbd是否是合成的,只有在实现aop的时候synthetic的值才为true,
// 并且是否实现了InstantiationAwareBeanPostProcessor接口
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 获取类型
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
// 是否解析了
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}

12.2.2 AbstractAutowireCapableBeanFactory#doCreateBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#doCreateBean

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {

// Instantiate the bean.
// 这个beanWrapper是用来持有创建出来的bean对象的
BeanWrapper instanceWrapper = null;
// 获取factoryBean实例缓存
if (mbd.isSingleton()) {
// 如果是单例对象,从factorybean实例缓存中移除当前bean定义信息
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
// 没有就创建实例
if (instanceWrapper == null) {
// 创建Bean对象,并且将对象包裹在 BeanWrapper 中
// 根据执行bean使用对应的策略创建新的实例,如,工厂方法,构造函数主动注入、简单初始化
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 再从Wrapper中把Bean原始对象(非代理) 这个时候这个Bean就有地址值了,就能被引用了
final Object bean = instanceWrapper.getWrappedInstance();
// 获取具体的bean对象的Class属性
Class<?> beanType = instanceWrapper.getWrappedClass();
// 如果不等于NullBean类型,那么修改目标类型
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}

// Allow post-processors to modify the merged bean definition.
// 允许 beanPostProcessor 去修改合并的 beanDefinition
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
// MergedBeanDefinitionPostProcessor 后置处理器修改合并bean的定义
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}

// Eagerly cache singletons to be able to resolve circular references
// even when triggered by lifecycle interfaces like BeanFactoryAware.
// 判断当前bean是否需要提前曝光:单例&允许循环依赖&当前bean正在创建中,检测循环依赖
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 解决循环引用问题,需要提前暴露引用
// 为避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
// 初始化bean实例
Object exposedObject = bean;
try {
// 使用Bean定义中的属性值填充给定BeanWrapper中的Bean实例
// 对bean的属性进行填充,将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean
populateBean(beanName, mbd, instanceWrapper);
// 使用工厂回调以及初始化方法和bean后处理器初始化给定的bean实例。执行初始化逻辑
// 1. BeanNameAware#setBeanName、BeanClassLoaderAware#setBeanClassLoader、BeanFactoryAware#setBeanFactory
// 2. BeanPostProcessor#postProcessBeforeInitialization
// 3. InitializingBean#afterPropertiesSet 和 调用配置的 initMethod 方法
// 4. BeanPostProcessor#postProcessAfterInitialization
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}

if (earlySingletonExposure) {
// 尝试从缓存中获取单例,注意后面的参数为false,表示不从第三级缓存singletonFactories中获取
// 为什么呢?因为这里不允许循环依赖
Object earlySingletonReference = getSingleton(beanName, false);
// 如果不为null,就会进入if条件中,因为earlySingletonReference不为null,说明存在循环引用,
// 为什么呢?因为第一个处理的时候,会将引用放到singletonFactories缓存中,当循环依赖注入的时候,
// 会通过singletonFactories中拿到提前暴露的引用,然后放到第二级缓存earlySingletonObjects中。
// 所以,在这里拿到了earlySingletonReference,表明存在循环引用。
// earlySingletonReference只有在检测到有循环依赖的情况下才会不为空
if (earlySingletonReference != null) {
// 如果相等,那么就什么也不做,将earlySingletonReference返回回去即可
// 如果exposedObject没有在初始化方法中被改变,也就是没有被增强
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
// 如果不相等,并且有其它bean依赖这个bean
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 拿到依赖这个bean的所有bean
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 如果存在已经创建完的bean(已经创建完的bean依赖该bean)
// 返回false说明依赖还没实例化好
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
// 防止对象被改变,造成的已创建对象中持有的对象和这个对象不一致。
// 因为bean创建后所依赖的bean一定是已经创建的
// actualDependentBeans不为空则表示当前bean创建后其依赖的bean却没有全部创建完,也就是说存在循环依赖
throw new BeanCurrentlyInCreationException(beanName,
"Bean with name '" + beanName + "' has been injected into other beans [" +
StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
"] in its raw version as part of a circular reference, but has eventually been " +
"wrapped. This means that said other beans do not use the final version of the " +
"bean. This is often the result of over-eager type matching - consider using " +
"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}

// Register bean as disposable.
try {
// 注册 DisposableBean 和 解析配置的 destroyMethod 方法
// 注册bean对象,方便后续在容器销毁的时候销毁对象
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

return exposedObject;
}

12.2.2.1 AbstractAutowireCapableBeanFactory#createBeanInstance

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#createBeanInstance

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
// 确认需要创建的bean实例的类可以实例化
Class<?> beanClass = resolveBeanClass(mbd, beanName);

if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}

// 判断当前beanDefinition中是否包含实例供应器,此处相当于一个回调方法,利用回调方法来创建bean
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}

// 如果工厂方法不为空则使用工厂方法初始化策略
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

// 一个类可能有多个构造器,所以Spring得根据参数个数、类型确定需要调用的构造器
// 在使用构造器创建实例后,Spring会将解析过后确定下来的构造器或工厂方法保存在缓存中,避免再次创建相同bean时再次解析

// Shortcut when re-creating the same bean...
// 标记下,防止重复创建同一个bean
boolean resolved = false;
// 是否需要自动装配
boolean autowireNecessary = false;
// 如果没有参数
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
// 因为一个类可能由多个构造函数,所以需要根据配置文件中配置的参数或传入的参数来确定最终调用的构造函数。
// 因为判断过程会比较,所以spring会将解析、确定好的构造函数缓存到BeanDefinition中的resolvedConstructorOrFactoryMethod字段中。
// 在下次创建相同时直接从RootBeanDefinition中的属性resolvedConstructorOrFactoryMethod缓存的值获取,避免再次解析
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
// 有构造参数的或者工厂方法
if (resolved) {
// 构造器有参数
if (autowireNecessary) {
// 构造函数自动注入
return autowireConstructor(beanName, mbd, null, null);
}
else {
// 使用默认构造函数构造
return instantiateBean(beanName, mbd);
}
}

// Candidate constructors for autowiring?
// 从bean后置处理器中为自动装配寻找构造方法, 有且仅有一个有参构造或者有且仅有@Autowired注解构造
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
// 以下情况符合其一即可进入
// 1、存在可选构造方法
// 2、自动装配模型为构造函数自动装配
// 3、给BeanDefinition中设置了构造参数值
// 4、有参与构造函数参数列表的参数
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}

// Preferred constructors for default construction?
// 找出最合适的默认构造方法
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}

// No special handling: simply use no-arg constructor.
// 使用默认无参构造函数创建对象,如果没有无参构造且存在多个有参构造且没有@AutoWired注解构造,会报错
return instantiateBean(beanName, mbd);
}

12.2.2.1.1 ConstructorResolver#autowireConstructor

**定位: ** org.springframework.beans.factory.support.ConstructorResolver#autowireConstructor

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
public BeanWrapper autowireConstructor(String beanName, RootBeanDefinition mbd,
@Nullable Constructor<?>[] chosenCtors, @Nullable Object[] explicitArgs) {

// 实例化BeanWrapper。是包装bean的容器
BeanWrapperImpl bw = new BeanWrapperImpl();
// 给包装对象设置一些属性
this.beanFactory.initBeanWrapper(bw);

// spring对这个bean进行实例化使用的构造函数
Constructor<?> constructorToUse = null;
// spring执行构造函数使用的是参数封装类
ArgumentsHolder argsHolderToUse = null;
// 参与构造函数实例化过程的参数
Object[] argsToUse = null;

// 如果传入参数的话,就直接使用传入的参数
if (explicitArgs != null) {
// 让argsToUse引用explicitArgs
argsToUse = explicitArgs;
}
// 没有传入参数的话就走else
else {
//声明一个要解析的参数值数组,默认为null
Object[] argsToResolve = null;
synchronized (mbd.constructorArgumentLock) {
// 获取BeanDefinition中解析完成的构造函数
constructorToUse = (Constructor<?>) mbd.resolvedConstructorOrFactoryMethod;
// BeanDefinition中存在构造函数并且存在构造函数的参数,赋值进行使用
if (constructorToUse != null && mbd.constructorArgumentsResolved) {
// Found a cached constructor...
// 从缓存中找到了构造器,那么继续从缓存中寻找缓存的构造器参数
argsToUse = mbd.resolvedConstructorArguments;
if (argsToUse == null) {
// 没有缓存的参数,就需要获取配置文件中配置的参数
argsToResolve = mbd.preparedConstructorArguments;
}
}
}
// 如果缓存中没有缓存的参数的话,即argsToResolve不为空,就需要解析配置的参数
if (argsToResolve != null) {
// 解析参数类型,比如将配置的String类型转换为list、boolean等类型
argsToUse = resolvePreparedArguments(beanName, mbd, bw, constructorToUse, argsToResolve, true);
}
}

// 如果constructorToUse为null或者argsToUser为null
if (constructorToUse == null || argsToUse == null) {
// Take specified constructors, if any.
// 如果传入的构造器数组不为空,就使用传入的过后早期参数,否则通过反射获取class中定义的构造器
Constructor<?>[] candidates = chosenCtors;
// 如果candidates为null
if (candidates == null) {
// 获取mbd的Bean类
Class<?> beanClass = mbd.getBeanClass();
try {
// 使用public的构造器或者所有构造器
candidates = (mbd.isNonPublicAccessAllowed() ?
beanClass.getDeclaredConstructors() : beanClass.getConstructors());
}
// 捕捉获取beanClass的构造函数发出的异常
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Resolution of declared constructors on bean Class [" + beanClass.getName() +
"] from ClassLoader [" + beanClass.getClassLoader() + "] failed", ex);
}
}

// 如果candidateList只有一个元素 且 没有传入构造函数值 且 mbd也没有构造函数参数值
if (candidates.length == 1 && explicitArgs == null && !mbd.hasConstructorArgumentValues()) {
// 获取candidates中唯一的方法
Constructor<?> uniqueCandidate = candidates[0];
// 如果uniqueCandidate不需要参数
if (uniqueCandidate.getParameterCount() == 0) {
// 使用mdb的构造函数字段的通用锁【{@link RootBeanDefinition#constructorArgumentLock}】进行加锁以保证线程安全
synchronized (mbd.constructorArgumentLock) {
// 让mbd缓存已解析的构造函数或工厂方法
mbd.resolvedConstructorOrFactoryMethod = uniqueCandidate;
// 让mbd标记构造函数参数已解析
mbd.constructorArgumentsResolved = true;
// 让mbd缓存完全解析的构造函数参数
mbd.resolvedConstructorArguments = EMPTY_ARGS;
}
// 使用constructorToUse生成与beanName对应的Bean对象,并将该Bean对象保存到bw中
bw.setBeanInstance(instantiate(beanName, mbd, uniqueCandidate, EMPTY_ARGS));
// 将bw返回出去
return bw;
}
}

// Need to resolve the constructor.
// 自动装配标识,以下有一种情况成立则为true,
// 1、传进来构造函数,证明spring根据之前代码的判断,知道应该用哪个构造函数,
// 2、BeanDefinition中设置为构造函数注入模型
boolean autowiring = (chosenCtors != null ||
mbd.getResolvedAutowireMode() == AutowireCapableBeanFactory.AUTOWIRE_CONSTRUCTOR);
// 定义一个用于存放解析后的构造函数参数值的ConstructorArgumentValues对象
ConstructorArgumentValues resolvedValues = null;

// 构造函数的最小参数个数
int minNrOfArgs;
// 如果传入了参与构造函数实例化的参数值,那么参数的数量即为最小参数个数
if (explicitArgs != null) {
// minNrOfArgs引用 explicitArgs 的数组长度
minNrOfArgs = explicitArgs.length;
}
else {
// 提取配置文件中的配置的构造函数参数
ConstructorArgumentValues cargs = mbd.getConstructorArgumentValues();
// 用于承载解析后的构造函数参数的值
resolvedValues = new ConstructorArgumentValues();
// 能解析到的参数个数
minNrOfArgs = resolveConstructorArguments(beanName, mbd, bw, cargs, resolvedValues);
}

// 对候选的构造函数进行排序,先是访问权限后是参数个数
// public权限参数数量由多到少
AutowireUtils.sortConstructors(candidates);
// 定义一个差异变量,变量的大小决定着构造函数是否能够被使用
int minTypeDiffWeight = Integer.MAX_VALUE;
// 不明确的构造函数集合,正常情况下差异值不可能相同
Set<Constructor<?>> ambiguousConstructors = null;
// 定义一个用于UnsatisfiedDependencyException的列表
LinkedList<UnsatisfiedDependencyException> causes = null;

// 循环候选的构造函数
for (Constructor<?> candidate : candidates) {
// 获取参数的个数
Class<?>[] paramTypes = candidate.getParameterTypes();

// 如果已经找到选用的构造函数或者需要的参数个数小于当前的构造函数参数个数则终止,前面已经经过了排序操作
if (constructorToUse != null && argsToUse != null && argsToUse.length > paramTypes.length) {
// Already found greedy constructor that can be satisfied ->
// do not look any further, there are only less greedy constructors left.
break;
}
// 如果本构造函数的参数列表数量小于要求的最小数量,则遍历下一个
if (paramTypes.length < minNrOfArgs) {
// 参数个数不相等
continue;
}

// 存放构造函数解析完成的参数列表
ArgumentsHolder argsHolder;
// 存在需要解析的构造函数参数
if (resolvedValues != null) {
try {
// 获取构造函数上的ConstructorProperties注解中的参数
String[] paramNames = ConstructorPropertiesChecker.evaluate(candidate, paramTypes.length);
// 如果没有上面的注解,则获取构造函数参数列表中属性的名称
if (paramNames == null) {
// 获取参数名称探索器
ParameterNameDiscoverer pnd = this.beanFactory.getParameterNameDiscoverer();
if (pnd != null) {
// 获取指定构造函数的参数名称
paramNames = pnd.getParameterNames(candidate);
}
}
// 根据名称和数据类型创建参数持有者
argsHolder = createArgumentArray(beanName, mbd, resolvedValues, bw, paramTypes, paramNames,
getUserDeclaredConstructor(candidate), autowiring, candidates.length == 1);
}
catch (UnsatisfiedDependencyException ex) {
if (logger.isTraceEnabled()) {
logger.trace("Ignoring constructor [" + candidate + "] of bean '" + beanName + "': " + ex);
}
// Swallow and try next constructor.
// 吞下并尝试下一个重载的构造函数
// 如果cause为null
if (causes == null) {
// 对cause进行实例化成LinkedList对象
causes = new LinkedList<>();
}
// 将ex添加到causes中
causes.add(ex);
continue;
}
}
// 不存在构造函数参数列表需要解析的参数
else {
// Explicit arguments given -> arguments length must match exactly.
// 如果参数列表的数量与传入进来的参数数量不相等,继续遍历,否则构造参数列表封装对象
if (paramTypes.length != explicitArgs.length) {
continue;
}
// 构造函数没有参数的情况
argsHolder = new ArgumentsHolder(explicitArgs);
}

// 计算差异量,根据要参与构造函数的参数列表和本构造函数的参数列表进行计算
int typeDiffWeight = (mbd.isLenientConstructorResolution() ?
argsHolder.getTypeDifferenceWeight(paramTypes) : argsHolder.getAssignabilityWeight(paramTypes));
// Choose this constructor if it represents the closest match.
// 本次的构造函数差异值小于上一个构造函数,则进行构造函数更换
if (typeDiffWeight < minTypeDiffWeight) {
// 将确定使用的构造函数设置为本构造
constructorToUse = candidate;
// 更换使用的构造函数参数封装类
argsHolderToUse = argsHolder;
// 更换参与构造函数实例化的参数
argsToUse = argsHolder.arguments;
// 差异值更换
minTypeDiffWeight = typeDiffWeight;
// 不明确的构造函数列表清空为null
ambiguousConstructors = null;
}
// 差异值相等,则表明构造函数不正常,放入异常集合
else if (constructorToUse != null && typeDiffWeight == minTypeDiffWeight) {
// 如果ambiguousFactoryMethods为null
if (ambiguousConstructors == null) {
// 初始化ambiguousFactoryMethods为LinkedHashSet实例
ambiguousConstructors = new LinkedHashSet<>();
// 将constructorToUse添加到ambiguousFactoryMethods中
ambiguousConstructors.add(constructorToUse);
}
// 将candidate添加到ambiguousFactoryMethods中
ambiguousConstructors.add(candidate);
}
}

// 以下两种情况会抛异常
// 1、没有确定使用的构造函数
// 2、存在模糊的构造函数并且不允许存在模糊的构造函数
if (constructorToUse == null) {
if (causes != null) {
UnsatisfiedDependencyException ex = causes.removeLast();
for (Exception cause : causes) {
this.beanFactory.onSuppressedException(cause);
}
throw ex;
}
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Could not resolve matching constructor " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)");
}
else if (ambiguousConstructors != null && !mbd.isLenientConstructorResolution()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Ambiguous constructor matches found in bean '" + beanName + "' " +
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities): " +
ambiguousConstructors);
}

/*
* 没有传入参与构造函数参数列表的参数时,对构造函数缓存到BeanDefinition中
* 1、缓存BeanDefinition进行实例化时使用的构造函数
* 2、缓存BeanDefinition代表的Bean的构造函数已解析完标识
* 3、缓存参与构造函数参数列表值的参数列表
*/
if (explicitArgs == null && argsHolderToUse != null) {
// 将解析的构造函数加入缓存
argsHolderToUse.storeCache(mbd, constructorToUse);
}
}

Assert.state(argsToUse != null, "Unresolved constructor arguments");
// 将构造的实例加入BeanWrapper中
bw.setBeanInstance(instantiate(beanName, mbd, constructorToUse, argsToUse));
return bw;
}

12.2.2.1.2 AbstractAutowireCapableBeanFactory#instantiateBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#instantiateBean

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
Object beanInstance;
final BeanFactory parent = this;
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
}
else {
// 获取实例化策略并且进行实例化操作
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
// 包装成BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}

12.2.2.1.3 AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#determineConstructorsFromBeanPostProcessors

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {

if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
// 从SmartInstantiationAwareBeanPostProcessor判断
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}

12.2.2.2 DefaultSingletonBeanRegistry#addSingletonFactory

**定位: ** org.springframework.beans.factory.support.DefaultSingletonBeanRegistry#addSingletonFactory

1
2
3
4
5
6
7
8
9
10
11
12
13
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
// 放到单例工厂里
this.singletonFactories.put(beanName, singletonFactory);
// 删除早期单例
this.earlySingletonObjects.remove(beanName);
// 添加到已注册
this.registeredSingletons.add(beanName);
}
}
}

12.2.2.3 AbstractAutowireCapableBeanFactory#populateBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#populateBean

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 如果beanWrapper为空
if (bw == null) {
// 如果mbd有需要设置的属性
if (mbd.hasPropertyValues()) {
// 抛出bean创建异常
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
// 没有可填充的属性,直接跳过
return;
}
}

// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
// 给任何实现了InstantiationAwareBeanPostProcessors的子类机会去修改bean的状态再设置属性之前,可以被用来支持类型的字段注入

// 否是"synthetic"。一般是指只有AOP相关的pointCut配置或者Advice配置才会将 synthetic设置为true
// 如果mdb是不是'synthetic' 且 工厂拥有InstantiationAwareBeanPostProcessor
boolean continueWithPropertyPopulation = true;

if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 遍历工厂中的BeanPostProcessor对象
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果 bp 是 InstantiationAwareBeanPostProcessor 实例
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// postProcessAfterInstantiation:一般用于设置属性
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}

if (!continueWithPropertyPopulation) {
return;
}

// PropertyValues:包含以一个或多个PropertyValue对象的容器,通常包括针对特定目标Bean的一次更新
// 如果mdb有PropertyValues就获取其PropertyValues
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

// 获取 mbd 的 自动装配模式
int resolvedAutowireMode = mbd.getResolvedAutowireMode();
// 如果 自动装配模式 为 按名称自动装配bean属性 或者 按类型自动装配bean属性
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// MutablePropertyValues:PropertyValues接口的默认实现。允许对属性进行简单操作,并提供构造函数来支持从映射 进行深度复制和构造
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
// 根据autotowire的名称(如适用)添加属性值
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
// 通过bw的PropertyDescriptor属性名,查找出对应的Bean对象,将其添加到newPvs中
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
// 根据自动装配的类型(如果适用)添加属性值
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 通过bw的PropertyDescriptor属性类型,查找出对应的Bean对象,将其添加到newPvs中
autowireByType(beanName, mbd, bw, newPvs);
}
// 让pvs重新引用newPvs,newPvs此时已经包含了pvs的属性值以及通过AUTOWIRE_BY_NAME,AUTOWIRE_BY_TYPE自动装配所得到的属性值
pvs = newPvs;
}

//工厂是否拥有InstantiationAwareBeanPostProcessor
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// mbd.getDependencyCheck(),默认返回 DEPENDENCY_CHECK_NONE,表示 不检查
// 是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

// 经过筛选的PropertyDescriptor数组,存放着排除忽略的依赖项或忽略项上的定义的属性
PropertyDescriptor[] filteredPds = null;
// 如果工厂拥有InstantiationAwareBeanPostProcessor,那么处理对应的流程,主要是对几个注解的赋值工作包含的两个关键子类是CommonAnnoationBeanPostProcessor,AutowiredAnnotationBeanPostProcessor
if (hasInstAwareBpps) {
if (pvs == null) {
// 尝试获取mbd的PropertyValues
pvs = mbd.getPropertyValues();
}
// 遍历工厂内的所有后置处理器
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 如果 bp 是 InstantiationAwareBeanPostProcessor 的实例
if (bp instanceof InstantiationAwareBeanPostProcessor) {
// 将 bp 强转成 InstantiationAwareBeanPostProcessor 对象
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// postProcessProperties:在工厂将给定的属性值应用到给定Bean之前,对它们进行后处理,不需要任何属性扫描符。该回调方法在未来的版本会被删掉。
// -- 取而代之的是 postProcessPropertyValues 回调方法。
// 让ibp对pvs增加对bw的Bean对象的propertyValue,或编辑pvs的propertyValue
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
// mbd.allowCaching:是否允许缓存,默认时允许的。缓存除了可以提高效率以外,还可以保证在并发的情况下,返回的PropertyDesciptor[]永远都是同一份
// 从bw提取一组经过筛选的PropertyDescriptor,排除忽略的依赖项或忽略项上的定义的属性
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// postProcessPropertyValues:一般进行检查是否所有依赖项都满足,例如基于"Require"注释在 bean属性 setter,
// -- 替换要应用的属性值,通常是通过基于原始的PropertyValues创建一个新的MutablePropertyValue实例, 添加或删除特定的值
// -- 返回的PropertyValues 将应用于bw包装的bean实例 的实际属性值(添加PropertyValues实例到pvs 或者 设置为null以跳过属性填充)
// 回到ipd的postProcessPropertyValues方法
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
// 如果pvsToUse为null,将终止该方法精致,以跳过属性填充
if (pvsToUse == null) {
return;
}
}
// 让pvs引用pvsToUse
pvs = pvsToUse;
}
}
}
// 如果需要依赖检查
if (needsDepCheck) {
if (filteredPds == null) {
// 从bw提取一组经过筛选的PropertyDescriptor,排除忽略的依赖项或忽略项上的定义的属性
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 检查依赖项:主要检查pd的setter方法需要赋值时,pvs中有没有满足其pd的需求的属性值可供其赋值
checkDependencies(beanName, mbd, filteredPds, pvs);
}

if (pvs != null) {
// 应用给定的属性值,解决任何在这个bean工厂运行时其他bean的引用。必须使用深拷贝,所以我们 不会永久地修改这个属性
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
12.2.2.3.1 AbstractAutowireCapableBeanFactory#autowireByName

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByName

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
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

// 获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历属性名
for (String propertyName : propertyNames) {
// 如果该bean工厂有propertyName的beanDefinition或外部注册的singleton实例
if (containsBean(propertyName)) {
// 获取该工厂中propertyName的bean对象
Object bean = getBean(propertyName);
// 将propertyName,bean添加到pvs中
pvs.add(propertyName, bean);
// 注册propertyName与beanName的依赖关系
registerDependentBean(propertyName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Added autowiring by name from bean name '" + beanName +
"' via property '" + propertyName + "' to bean named '" + propertyName + "'");
}
}
else {
if (logger.isTraceEnabled()) {
logger.trace("Not autowiring property '" + propertyName + "' of bean '" + beanName +
"' by name: no matching bean found");
}
}
}
}
12.2.2.3.2 AbstractAutowireCapableBeanFactory#autowireByType

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#autowireByType

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

// 获取工厂的自定义类型转换器
TypeConverter converter = getCustomTypeConverter();
// 如果没有配置自定义类型转换器
if (converter == null) {
// 使用bw作为类型转换器
converter = bw;
}

// 存放所有候选Bean名的集合
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
// 获取bw中有setter方法 && 非简单类型属性 && mbd的PropertyValues中没有该pd的属性名的 PropertyDescriptor 属性名数组
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 遍历属性名数组
for (String propertyName : propertyNames) {
try {
// PropertyDescriptor:表示JavaBean类通过存储器导出一个属性
// 从bw中获取propertyName对应的PropertyDescriptor
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
// 不要尝试按类型自动装配对象:永远是有意义的,即使它在技术上是一个不满意,复杂属性
// 如果pd的属性值类型不是 Object
if (Object.class != pd.getPropertyType()) {
// 获取pd属性的Setter方法的方法参数包装对象
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
// 判断bean对象是否是PriorityOrder实例,如果不是就允许急于初始化来进行类型匹配。
// eager为true时会导致初始化lazy-init单例和由FactoryBeans(或带有"factory-bean"引用的工厂方法)创建 的对象以进行类型检查
boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
// AutowireByTypeDependencyDescriptor:根据类型依赖自动注入的描述符,重写了 getDependencyName() 方法,使其永远返回null
// 将 methodParam 封装包装成AutowireByTypeDependencyDescriptor对象
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 根据据desc的依赖类型解析出与descriptor所包装的对象匹配的候选Bean对象
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
// 如果autowiredArgument不为null
if (autowiredArgument != null) {
// 将propertyName.autowiredArgument作为键值添加到pvs中
pvs.add(propertyName, autowiredArgument);
}
// 遍历所有候选Bean名集合
for (String autowiredBeanName : autowiredBeanNames) {
// 注册beanName与dependentBeanNamed的依赖关系
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
// 将候选Bean名集合清空
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
// 捕捉自动装配时抛出的Bean异常,重新抛出 不满足依赖异常
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
12.2.2.3.3 AbstractAutowireCapableBeanFactory#applyPropertyValues

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyPropertyValues

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs.isEmpty()) {
return;
}

// 如果有安全管理器,且bw是BeanWrapperImpl的实例
if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
// 设置bw的安全上下文为工厂的访问控制上下文
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}

// MutablePropertyValues:PropertyValues接口的默认实现。
// 允许对属性进行简单操作,并提供构造函数来支持从映射 进行深度复制和构造
MutablePropertyValues mpvs = null;
// 原始属性列表
List<PropertyValue> original;

// 如果pvs是MutablePropertyValues
if (pvs instanceof MutablePropertyValues) {
// 类型强制转换
mpvs = (MutablePropertyValues) pvs;
// isConverted:返回该holder是否只包含转换后的值(true),或者是否仍然需要转换这些值
// 如果mpvs只包含转换后的值
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
// 已完成,直接返回
bw.setPropertyValues(mpvs);
return;
}
catch (BeansException ex) {
//捕捉Bean异常,重新抛出Bean创佳异常:错误设置属性值。
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
// 获取mpvs的PropertyValue列表
original = mpvs.getPropertyValueList();
}
else {
// 获取pvs的PropertyValue对象数组,并将其转换成列表
original = Arrays.asList(pvs.getPropertyValues());
}

// 获取用户自定义类型转换器
TypeConverter converter = getCustomTypeConverter();
// 如果转换器为空,则直接把包装类赋值给converter
if (converter == null) {
converter = bw;
}
// BeanDefinitionValueResolver:在bean工厂实现中使用Helper类,它将beanDefinition对象中包含的值解析为应用于 目标bean实例的实际值
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

// Create a deep copy, resolving any references for values.
// 创建一个深拷贝,解析任何值引用
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
//是否还需要解析标记
boolean resolveNecessary = false;
// 遍历属性,将属性转换为对应类的对应属性的类型
for (PropertyValue pv : original) {
// 如果该属性已经解析过
if (pv.isConverted()) {
// 将pv添加到deepCopy中
deepCopy.add(pv);
}
// 如果属性没有被解析过
else {
// 获取属性的名字
String propertyName = pv.getName();
// 获取未经类型转换的值
Object originalValue = pv.getValue();
// AutowiredPropertyMarker.INSTANCE:自动生成标记的规范实例
if (originalValue == AutowiredPropertyMarker.INSTANCE) {
// 获取propertyName在bw中的setter方法
Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
// 如果setter方法为null
if (writeMethod == null) {
// 抛出非法参数异常:自动装配标记属性没有写方法。
throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
}
// 将writerMethod封装到DependencyDescriptor对象
originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
}
// 交由valueResolver根据pv解析出originalValue所封装的对象
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
// 默认转换后的值是刚解析出来的值
Object convertedValue = resolvedValue;
// 可转换标记: propertyName是否bw中的可写属性 && prepertyName不是表示索引属性或嵌套属性(如果propertyName中有'.'||'['就认为是索引属性或嵌套属性)
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
// 如果可转换
if (convertible) {
// 将resolvedValue转换为指定的目标属性对象
convertedValue = convertForProperty(resolvedValue, propertyName, bw, converter);
}
// Possibly store converted value in merged bean definition,
// in order to avoid re-conversion for every created bean instance.
// 可以将转换后的值存储合并后BeanDefinition中,以避免对每个创建的Bean实例进行重新转换
// 如果resolvedValue与originalValue是同一个对象
if (resolvedValue == originalValue) {
// 如果可转换
if (convertible) {
// 将convertedValue设置到pv中
pv.setConvertedValue(convertedValue);
}
// 将pv添加到deepCopy中
deepCopy.add(pv);
}
// TypedStringValue:类型字符串的Holder,这个holder将只存储字符串值和目标类型。实际得转换将由Bean工厂执行
// 如果可转换 && originalValue是TypedStringValue的实例 && orginalValue不是标记为动态【即不是一个表达式】&&
// convertedValue不是Collection对象 或 数组
else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
// 将convertedValue设置到pv中
pv.setConvertedValue(convertedValue);
// 将pv添加到deepCopy中
deepCopy.add(pv);
}
else {
// 标记还需要解析
resolveNecessary = true;
// 根据pv,convertedValue构建PropertyValue对象,并添加到deepCopy中
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
// mpvs不为null && 已经不需要解析
if (mpvs != null && !resolveNecessary) {
// 将此holder标记为只包含转换后的值
mpvs.setConverted();
}

// Set our (possibly massaged) deep copy.
try {
// 按原样使用deepCopy构造一个新的MutablePropertyValues对象然后设置到bw中以对bw的属性值更新
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
}
catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}

12.2.2.4 AbstractAutowireCapableBeanFactory#initializeBean

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#initializeBean

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// Aware接口处理器, 调用 BeanNameAware#setBeanName、BeanClassLoaderAware#setBeanClassLoader、BeanFactoryAware#setBeanFactory
if (System.getSecurityManager() != null) {
// 以特权的方式执行回调bean中的Aware接口方法
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
invokeAwareMethods(beanName, bean);
}

// 调用 BeanPostProcessor#postProcessBeforeInitialization
Object wrappedBean = bean;
// 如果mdb不为null || mbd不是"synthetic"。一般是指只有AOP相关的prointCut配置或者Advice配置才会将 synthetic设置为true
if (mbd == null || !mbd.isSynthetic()) {
// 将BeanPostProcessors应用到给定的现有Bean实例,调用它们的postProcessBeforeInitialization初始化方法。
// 返回的Bean实例可能是原始Bean包装器
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

// 调用 InitializingBean#afterPropertiesSet
// 反射调用配置的 initMethod 方法
try {
// 调用初始化方法,先调用bean的InitializingBean接口方法,后调用bean的自定义初始化方法
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
// 调用 BeanPostProcessor#postProcessAfterInitialization
if (mbd == null || !mbd.isSynthetic()) {
// 将BeanPostProcessors应用到给定的现有Bean实例,调用它们的postProcessAfterInitialization方法。
// 返回的Bean实例可能是原始Bean包装器
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

// 返回包装后的Bean
return wrappedBean;
}
12.2.2.4.1 AbstractAutowireCapableBeanFactory#invokeAwareMethods

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeAwareMethods

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
private void invokeAwareMethods(final String beanName, final Object bean) {
if (bean instanceof Aware) {
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
12.2.2.4.2 AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {

// 初始化返回结果为existingBean
Object result = existingBean;
// 遍历该工厂创建的bean的BeanPostProcessors列表
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// postProcessBeforeInitialization:在任何Bean初始化回调之前(如初始化Bean的afterPropertiesSet或自定义的init方法)
// 将此BeanPostProcessor 应用到给定的新Bean实例。Bean已经填充了属性值。返回的Bean实例可能时原始Bean的包装器。
// 默认实现按原样返回给定的 Bean
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
// 直接返回result,中断其后续的BeanPostProcessor处理
return result;
}
// 让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装
result = current;
}
// 返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
return result;
}
12.2.2.4.2 AbstractAutowireCapableBeanFactory#invokeInitMethods

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#invokeInitMethods

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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {

// isInitializingBean:当Bean的所有属性都被BeanFactory设置好后,Bean需要执行相应的接口:例如执行自定义初始化,或者仅仅是检查所有强制属性是否已经设置好。
// bean是InitializingBean实例标记
boolean isInitializingBean = (bean instanceof InitializingBean);
// isExternallyManagedInitMethod是否外部受管理的Init方法名
// 如果 bean是InitializingBean实例 && (mdb为null || 'afterPropertiesSet' 不是外部受管理的Init方法名)
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
// 以特权方式调用 bean的 afterPropertiesSet 方法
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
// 调用 bean 的 afterPropertiesSet 方法
((InitializingBean) bean).afterPropertiesSet();
}
}

// 如果mbd不为null && bean不是NullBean类
if (mbd != null && bean.getClass() != NullBean.class) {
// 获取mbd指定的初始化方法名
String initMethodName = mbd.getInitMethodName();
// 如果initMethodName不为null && (bean不是InitializingBean实例 && 'afterPropertiesSet'是初始化方法名)
// && initMethodName不是外部受管理的Init方法名
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// 在bean上调用指定的自定义init方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}

protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {

// 获取初始化方法名称
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
// 获取初始化方法
Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

if (initMethod == null) {
if (mbd.isEnforceInitMethod()) {
throw new BeanDefinitionValidationException("Could not find an init method named '" +
initMethodName + "' on bean with name '" + beanName + "'");
}
else {
if (logger.isTraceEnabled()) {
logger.trace("No default init method named '" + initMethodName +
"' found on bean with name '" + beanName + "'");
}
// Ignore non-existent default lifecycle methods.
return;
}
}

if (logger.isTraceEnabled()) {
logger.trace("Invoking init method '" + initMethodName + "' on bean with name '" + beanName + "'");
}
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);

if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
ReflectionUtils.makeAccessible(methodToInvoke);
return null;
});
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () ->
methodToInvoke.invoke(bean), getAccessControlContext());
}
catch (PrivilegedActionException pae) {
InvocationTargetException ex = (InvocationTargetException) pae.getException();
throw ex.getTargetException();
}
}
else {
try {
ReflectionUtils.makeAccessible(methodToInvoke);
// 反射执行
methodToInvoke.invoke(bean);
}
catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}
12.2.2.4.3 AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {

// 初始化结果对象为result,默认引用existingBean
Object result = existingBean;
// 遍历该工厂创建的bean的BeanPostProcessors列表
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// 回调BeanPostProcessor#postProcessAfterInitialization来对现有的bean实例进行包装
Object current = processor.postProcessAfterInitialization(result, beanName);
// 一般processor对不感兴趣的bean会回调直接返回result,使其能继续回调后续的BeanPostProcessor;
// 但有些processor会返回null来中断其后续的BeanPostProcessor
if (current == null) {
// 如果current为null,直接返回result,中断其后续的BeanPostProcessor处理
return result;
}
// 让result引用processor的返回结果,使其经过所有BeanPostProcess对象的后置处理的层层包装
result = current;
}
// 返回经过所有BeanPostProcess对象的后置处理的层层包装后的result
return result;
}

12.2.2.5 AbstractAutowireCapableBeanFactory#registerDisposableBeanIfNecessary

**定位: ** org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory#registerDisposableBeanIfNecessary

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
// 有销毁接口
if (!mbd.isPrototype() && requiresDestruction(bean, mbd)) {
// 单例的情况,注册销毁回调
if (mbd.isSingleton()) {
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// DisposableBean interface, custom destroy method.
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
else {
// A bean with a custom scope...
// 自定义的,注册Scope
Scope scope = this.scopes.get(mbd.getScope());
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + mbd.getScope() + "'");
}
scope.registerDestructionCallback(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
}
}
}