1. 目录

[TOC]

2. 说明

初始化bean的过程一般是放在getBean的匿名内部类创建中,一般不主动调起

3. 依赖分析

DefaultListableBeanFactory的创建bean的方法主要依赖AbstractAutowireCapableBeanFactory

4. 源码分析

这里主要分析AbstractAutowireCapableBeanFactory

4.1. createBean()

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
// AbstractAutowireCapableBeanFactory
@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;

//解析BeanClass 因为RootBeanDefinition可能只有类的全路径String信息,不一定是可以用的Class,因此需要解析
//见下
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
//这里一般的bean是不走这里,解析得到hasBeanClass的
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}

try {
//准备方法覆盖, <lookup-method>、<replaced-method> 标签对应的处理,
//这里解析标签早就放在了BeanDifinition中了
mbdToUse.prepareMethodOverrides();
}
catch (BeanDefinitionValidationException ex) {
throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
beanName, "Validation of method overrides failed", ex);
}

try {
//获取特殊处理的bean,如池化的一些bean,这里允许自定义实例化bean,不走后续doCreateBean逻辑
//初步怀疑aop代理和动态代理跟这里有关系
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 {
//真正执行创建bean的过程
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);
}
}

mbdToUse.prepareMethodOverrides()
Spring允许在Bean配置中使用等标签来定义方法覆盖。通过方法覆盖,我们可以在Spring容器中动态地替换容器中某个Bean的方法实现,以达到定制化的需求。

在mbdToUse.prepareMethodOverrides()方法中,Spring会检查Bean的配置信息,解析其中定义的方法覆盖配置,并作出相应的处理。具体而言,它会扫描Bean定义中的方法覆盖配置,然后进行解析和处理,最终生成适当的方法覆盖策略。

需要注意的是,mbdToUse.prepareMethodOverrides()方法是在Bean创建过程中被调用的,目的是为了在实例化和初始化Bean之前,对方法覆盖的配置进行解析和准备工作。这样,在Bean创建完成后,我们就可以通过方法覆盖来动态地改变Bean中某个方法的实现。

4.1.1. resolveBeanClass()

解析BeanClass 因为RootBeanDefinition可能只有类的全路径String信息,不一定是可以用的Class,如果是全路径信息,则需要拿到对应的类信息

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
@Nullable
protected Class<?> resolveBeanClass(RootBeanDefinition mbd, String beanName, Class<?>... typesToMatch)
throws CannotLoadBeanClassException {

try {
//判定是否是类,是的话就返回了
if (mbd.hasBeanClass()) {
return mbd.getBeanClass();
}
//安全相关不管,直接看else分支
if (System.getSecurityManager() != null) {
return AccessController.doPrivileged((PrivilegedExceptionAction<Class<?>>)
() -> doResolveBeanClass(mbd, typesToMatch), getAccessControlContext());
}
else {
//解析beanClass
return doResolveBeanClass(mbd, typesToMatch);
}
}
catch (PrivilegedActionException pae) {
ClassNotFoundException ex = (ClassNotFoundException) pae.getException();
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (ClassNotFoundException ex) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), ex);
}
catch (LinkageError err) {
throw new CannotLoadBeanClassException(mbd.getResourceDescription(), beanName, mbd.getBeanClassName(), err);
}
}

这里的 mbd.hasBeanClass()RootBeanDefinition内部就是判定了beanClass是不是类,不是就需要通过doResolveBeanClass()解析
doResolveBeanClass() 方法主要是解析string的,其内部暂时不去分析了,关键的处理为三个地方

  • return dynamicLoader.loadClass(className);
  • return ClassUtils.forName(className, dynamicLoader);
  • return mbd.resolveBeanClass(beanClassLoader);

这三个地方均是解析成class的

4.1.2. resolveBeforeInstantiation()

初步怀疑aop代理和动态代理跟这里有关系

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 在BeanDefinition中加了一个标记,保证这里只走一次
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {

//解析真实的bean类型,跟factoryMethodName等扩展有关,不继续探究了
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;
}

这里的前置处理、后置处理涉及到同一个接口InstantiationAwareBeanPostProcessor

前置方法只要有一个实例化成功了bean就停止解析,返回数据
后置方法只要有一个解析变成了空的,就停止解析
从这逻辑看来这个接口是配合接口集合使用的,而且会相互影响,因此spring建议项目里不要使用此接口做扩展

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
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
return result;
}
}
}
return null;
}
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {

Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}

InstantiationAwareBeanPostProcessor 后续单独分析其扩展

4.1.3. 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
protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
throws BeanCreationException {

//BeanWrapper,即bean的包装类,内部有bean的实例,同时包含bean的一些方法,属性等,方便调用配置属性
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}

//创建BeanWapper,见下
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}

// Allow post-processors to modify the merged bean definition.
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//对合并后的 BeanDefinition 进行进一步的修改,例如修改属性的值、添加自定义的注解或标记等。
//这对于一些复杂的场景,例如多个模块的配置合并、动态设置 Bean 的属性等非常有用,
//也可以拿来整体记录beanName和BeanDefinition的信息
//此处内部方法在循环调用 MergedBeanDefinitionPostProcessor 接口,每一个接口均要处理一次
//一般没啥修改
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}

//是否需要早期暴露,需要早期暴露的,就在这里加入到三级缓存中
//普通的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");
}
//添加到三级缓存中
//这里同样有一个匿名内部类ObjectFactory,同getBean中的类似
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
//填充bean,填充bean的属性相关,见下文
populateBean(beanName, mbd, instanceWrapper);
//初始化bean,包括注入,生命周期钩子函数、BeanPostProcessor等
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);
}
}

//是早期的单例bean则获取bean
if (earlySingletonExposure) {
//获取bean ,这里一般是获取到null,这不还正在创建过程嘛,即使创建好了也会在createBean的getSingleton匿名内部类方法完成后加入一级缓存
Object earlySingletonReference = getSingleton(beanName, false);
if (earlySingletonReference != null) {
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
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 " +
"'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
}
}
}
}
try {
//注册销毁事件,这个暂时不考虑
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}

return exposedObject;
}

4.1.3.1. 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
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// 解析出beanClass,准备实例化
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());
}

//一般为空,先不管
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//一般为空,先不管
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

//这里有配置<factory-method>的时候处理,先不管
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
//上面不走这里也不会走,
if (resolved) {
if (autowireNecessary) {
return autowireConstructor(beanName, mbd, null, null);
}
else {
return instantiateBean(beanName, mbd);
}
}
//下面是构造器的情况,有构造器则通过以下处理返回构造器创建
//获取到构造器,这里有一个扩展接口,见下
//一般的bean返回为空,并非类里真正的构造器
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
return autowireConstructor(beanName, mbd, ctors, args);
}
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
return autowireConstructor(beanName, mbd, ctors, null);
}
//只有无参构造器则走以下逻辑,初始化Bean的过程
return instantiateBean(beanName, mbd);
}
4.1.3.1.1. determineConstructorsFromBeanPostProcessors()

获取到构造器,这里一般的对象返回为空,所以这里的构造器并非为实际类里的构造器
SmartInstantiationAwareBeanPostProcessor 扩展单独处理

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

if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
//根据实现拿到构造器
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
return ctors;
}
}
}
}
return null;
}
4.1.3.1.2. instantiateBean() 实例化bean
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
protected BeanWrapper instantiateBean(String beanName, RootBeanDefinition mbd) {
try {
Object beanInstance;
//安全相关,不管,直接走else分支
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged(
(PrivilegedAction<Object>) () -> getInstantiationStrategy().instantiate(mbd, beanName, this),
getAccessControlContext());
}
else {
//获取到实例 getInstantiationStrategy() 得到 SimpleInstantiationStrategy,默认配置即为此
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, this);
}

//封装BeanWrapper,没有其它过多的逻辑,不管
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
//初始化BeanWrapper,往BeanWrapper添加一些东西,这里先不管了,目的就是实例化了bean并且封装成BeanWrapper
initBeanWrapper(bw);
return bw;
}
catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}
4.1.3.1.2.1. SimpleInstantiationStrategy#instantiate() 简单策略下的实例化流程
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
// SimpleInstantiationStrategy.java
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// 非CGLIB下走if分支,CGLIB走else分支
// Don't override the class with CGLIB if no overrides.
if (!bd.hasMethodOverrides()) {

//构造器相关,
Constructor<?> constructorToUse;
synchronized (bd.constructorArgumentLock) {
//普通bean不为空,可以找到
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
if (constructorToUse == null) {
final Class<?> clazz = bd.getBeanClass();
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
if (System.getSecurityManager() != null) {
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
}
else {
constructorToUse = clazz.getDeclaredConstructor();
}
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
}
catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//实例化bean
return BeanUtils.instantiateClass(constructorToUse);
}
else {
// Must generate CGLIB subclass.
return instantiateWithMethodInjection(bd, beanName, owner);
}
}

BeanUtils.instantiateClass(constructorToUse) spring封装的通过构造器实例化bean的方法,可以理解和普通的差不多

4.1.3.2. addSingletonFactory()

这里依然由DefaultSingletonBeanRegistry类处理单例容器相关的逻辑
此处是第4个和容器相关的方法了,前面在getBean()的时候涉及到两个getSingle()和一个addSingleton()

1
2
3
4
5
6
7
8
9
10
11
12
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);
}
}
}

此处我们需要注意的是我们加入到三级缓存中的只是方法的调用,并没有生成bean实例,因此此种方式将实例化bean的过程延迟到从三级缓存中取数据即ObjectFactory.getObject()的时候

4.1.3.3. getEarlyBeanReference() 获取早期的引用

翻译:获取对指定bean的早期访问的引用,通常是为了解析循环引用。
实际上是处理SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference()
//todo 需要再深入理解

1
2
3
4
5
6
7
8
9
10
11
12
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}

4.1.3.4. populateBean() 填充Bean

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
// AbstractAutowireCapableBeanFactory.java
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
//校验是否为空,不管
if (bw == null) {
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
return;
}
}

// 执行InstantiationAwareBeanPostProcessor的后处理方法
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
return;
}
}
}
}

//拿到属性,主要有set 和get 方法的属性。PropertyValues会封装,使得拿到get和set方法更容易
//这是Java提供的类,
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

int resolvedAutowireMode = mbd.getResolvedAutowireMode();
//自动注入byType或byName的,一般是xml标签中配置的,如:
//<bean class="com.kewen.service.AClass" id="autowiredByNameService" autowire="byType"/>
//配置了之后只要有set方法就会自动注入,无需在写@Autowired或标签配置
//在代码中执行则需要在BeanDifinition完成阶段通过扩展函数拿到BeanDefinition修改其自动注入类型
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
//通过名字注入
autowireByName(beanName, mbd, bw, newPvs);
}
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
//通过类型注入
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}

boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

PropertyDescriptor[] filteredPds = null;
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
//循环执行InstantiationAwareBeanPostProcessor的
//postProcessProperties()和 postProcessPropertyValues()
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//@Autowired注解就是在这里通过AutowiredAnnotationBeanPostProcessor#postProcessProperties()完成的
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
checkDependencies(beanName, mbd, filteredPds, pvs);
}

if (pvs != null) {
//这个里面又很复杂,暂时不管
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

4.1.3.4.1. 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
29
// AbstractAutowireCapableBeanFactory.java
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

//解析得到名字
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
//调用getBean()初始化依赖的bean,依赖的bean成功初始化并拿到之后走回到这里
//因此这里和之前的获取创建在代码上便形成了一个环 getBean->createBean->getBean
//也就有可能导致循环依赖的出现
Object bean = getBean(propertyName);
//设置属性,类似于我们的set方法
pvs.add(propertyName, bean);
//记录依赖bean,这是一个缓存,方便其他地方判断
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");
}
}
}
}
4.1.3.4.2. 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
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}

Set<String> autowiredBeanNames = new LinkedHashSet<>(4);

//与autowireByName一样,拿到属性名
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
try {
PropertyDescriptor pd = bw.getPropertyDescriptor(propertyName);
if (Object.class != pd.getPropertyType()) {
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
//解析依赖,在这里拿到依赖的bean实例,这里也可能出现循环依赖
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
//设置属性,类似于我们的set方法
pvs.add(propertyName, autowiredArgument);
}
//
for (String autowiredBeanName : autowiredBeanNames) {
//记录依赖bean,这是一个缓存,方便其他地方判断
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
4.1.3.4.2.1. resolveDependency() 解析依赖

这里后面也是很复杂,大致逻辑还是拿到beanName,然后通过beanFactory.getBean()获取,我们目前只关注到解析处doResolveDependency(),后续可以单独研究根据类型注入

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
@Override
@Nullable
public Object resolveDependency(DependencyDescriptor descriptor, @Nullable String requestingBeanName,
@Nullable Set<String> autowiredBeanNames, @Nullable TypeConverter typeConverter) throws BeansException {

descriptor.initParameterNameDiscovery(getParameterNameDiscoverer());
//Optional 则返回optional类型
if (Optional.class == descriptor.getDependencyType()) {
return createOptionalDependency(descriptor, requestingBeanName);
}
//ObjectFactory 则返回ObjectFactory类型
else if (ObjectFactory.class == descriptor.getDependencyType() ||
ObjectProvider.class == descriptor.getDependencyType()) {
return new DependencyObjectProvider(descriptor, requestingBeanName);
}
//Jsr330Factory的处理,没关注过
else if (javaxInjectProviderClass == descriptor.getDependencyType()) {
return new Jsr330Factory().createDependencyProvider(descriptor, requestingBeanName);
}
else {
Object result = getAutowireCandidateResolver().getLazyResolutionProxyIfNecessary(
descriptor, requestingBeanName);
if (result == null) {
// 这里是做解析的,doResolveDependency()做了很多处理之后通过`beanFactory.getBean()`拿到bean
result = doResolveDependency(descriptor, requestingBeanName, autowiredBeanNames, typeConverter);
}
return result;
}
}

4.1.3.5. initializeBean() 初始化bean

此方法会真正初始化bean,包括各种生命周期扩展函数

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
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
//安全的,不管
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
//执行Aware方法,实现了BeanNameAware、BeanClassLoaderAware、BeanFactoryAware钩子函数的会调用
invokeAwareMethods(beanName, bean);
}

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 循环执行 BeanPostProcessor的postProcessBeforeInitialization()初始化前的方法
// 所有的BeanPostProcessor都在这里循环执行,一般情况下列表见下图
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
//执行初始化方法 InitializingBean、 @postConstruct、<init-method> 钩子函数在此执行
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
//循环执行,执行BeanPostProcessor的后处理操作,初始化完成的操作
//AOP动态代理就是在这里完成的,对应的处理器 AnnotationAwareAspectJAutoProxyCreator
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}

return wrappedBean;
}

BeanPostProcessor列表图:
cedd51db48d42db8643df44cf606f7e3

  • ApplicationConterxtAwareProcessor 处理 ApplicationConterxtAware
  • CommonAnnotationNeanPostProcessor继承InitDestroyAnnotationBeanPostProcessor
    它可以处理@PostConstruct
  • AutowiredAnnotationBeanPostProcessor 这里没啥用,它不是处理@Autowired的,@Autowired在注入bean的时候注入的
  • AnnotationAwareAspectJAutoProxyCreator这个在配置了切面代理的时候才会有的
4.1.3.5.1. invokeAwareMethods() 执行aware钩子函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private void invokeAwareMethods(String beanName, Object bean) {
if (bean instanceof Aware) {
//设置setBeanName
if (bean instanceof BeanNameAware) {
((BeanNameAware) bean).setBeanName(beanName);
}
//设置setBeanClassLoader
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
//设置setBeanFactory
if (bean instanceof BeanFactoryAware) {
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}
4.1.3.5.2. applyBeanPostProcessorsBeforeInitialization() 执行初始化前操作
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {

Object result = existingBean;
//循环执行初始化前操作,遇到为空的则打断返回,所以要注意返回为空值
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
4.1.3.5.3. 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
protected void invokeInitMethods(String beanName, Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {

//判定是否是InitializingBean并执行,不管if分支,
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isTraceEnabled()) {
logger.trace("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
((InitializingBean) bean).afterPropertiesSet();
}
}

if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
// <init-method> 执行,不往下了
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
4.1.3.5.4. applyBeanPostProcessorsAfterInitialization() 执行初始化后操作

大多数的BeanPostProcessor没有后处理方法,
目前有的类为

  • ApplicationListenerDetector,如过此bean为ApplicationListener的实现,则将监听器加入到上下文的applicationListeners
  • AnnotationAwareAspectJAutoProxyCreator,此类处理AOP动态代理的,将动态代理类封装好,返回代理之后的bean
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {

Object result = existingBean;
for (BeanPostProcessor processor : getBeanPostProcessors()) {
//这里同样是遇到有空的就打断返回
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}

4.1.3.6. getSingleton() 获取单例bean

这里和之前getBean中获取容器bean的方法一致,此处不生成早期对象,而getBean中是会生成的

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
@Nullable
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
Object singletonObject = this.singletonObjects.get(beanName);
//没有拿到又正在创建,则从二级缓存中拿,
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
singletonObject = this.earlySingletonObjects.get(beanName);
//如果允许早期创建则再获取一次,获取不到从三级缓存中加载,同时加入到二级缓存中,从三级缓存中移除
/*
if (singletonObject == null && allowEarlyReference) {
synchronized (this.singletonObjects) {
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) {
//这里会调用匿名内部类方法创建bean
singletonObject = singletonFactory.getObject();
this.earlySingletonObjects.put(beanName, singletonObject);
this.singletonFactories.remove(beanName);
}
}
}
}
}
*/
}
return singletonObject;
}

5. 总结

此处创建bean的过程还是从拿到BeanDefinition开始的

  1. 首先还是解析得到beanClass,然后在执行自定义的解析(若有),一般的项目这个没有
  2. 然后执行创建,创建时先判断有无构造器的预处理钩子函数(一般无)
  3. 实例化bean,并包装成BeanWrapper
  4. 得到实例化的bean之后,处理钩子函数MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition()
  5. 获取对早期的引用,处理钩子函数SmartInstantiationAwareBeanPostProcessor#getEarlyBeanReference()
  6. 加入到三级缓存
  7. 填充Bean
    1. 处理钩子函数InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation()
    2. 自动注入bean、
    3. 处理钩子函数InstantiationAwareBeanPostProcessor#postProcessPropertiespostProcessPropertyValues()
  8. 初始化bean
    1. 执行aware钩子函数
    2. 执行BeanPostProcessor#postProcessBeforeInitialization()
    3. 执行钩子函数InitializationBean<init-method>
    4. 执行BeanPostProcessor#applyBeanPostProcessorsAfterInitialization()
  9. 如果是早期的bean,则获取单例beangetSingleton此处会从一级或二级缓存中取,但是不会从三级中取

6. 注意事项

此处创建的时候会在实例化完成后加入三级缓存中,而getBean最开始便会从三级缓存中取,这两处是解决循环依赖的关键