抱歉,您的浏览器无法访问本站
本页面需要浏览器支持(启用)JavaScript
了解详情 >

SpringIOC-填充Bean

前言

​ 接着 Spring IoC:getBean详解,我们继续解析获取 bean 实例里的核心内容:创建 bean 实例。

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
/**
* Populate the bean instance in the given BeanWrapper with the property values
* from the bean definition.
* 依赖注入的核心方法

*/
@SuppressWarnings("deprecation") // for postProcessPropertyValues
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
// 2.bw为空时的处理
if (bw == null) {
if (mbd.hasPropertyValues()) {
// 2.1 如果bw为空,属性不为空,抛异常,无法将属性值应用于null实例
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
} else {
// Skip property population phase for null instance.
// 2.2 如果bw为空,属性也为空,则跳过
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.
// 用于标识是否继续之后的属性填充
//这里很有意思,写接口可以让所有类都不能依赖注入
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 3.1 如果mbd不是合成的 && 存在InstantiationAwareBeanPostProcessor,则遍历处理InstantiationAwareBeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 3.2 在bean实例化后,属性填充之前被调用,允许修改bean的属性,如果返回false,则跳过之后的属性填充
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
// 3.3 如果返回false,将continueWithPropertyPopulation赋值为false,代表要跳过之后的属性填充
//是否需要DI,依赖注入不需要直接返回
return;
}
}
}
}

PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);

int resolvedAutowireMode = mbd.getResolvedAutowireMode();

// 4.解析自动装配模式为AUTOWIRE_BY_NAME和AUTOWIRE_BY_TYPE(现在几乎不用)
if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 将 PropertyValues 封装成 MutablePropertyValues 对象
// MutablePropertyValues 允许对属性进行简单的操作,
// 并提供构造函数以支持Map的深度复制和构造。
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
// Add property values based on autowire by name if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
// 4.1 解析autowireByName的注入
autowireByName(beanName, mbd, bw, newPvs);
}
// Add property values based on autowire by type if applicable.
if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
// 4.2 解析autowireByType的注入
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
// 5.BeanFactory是否注册过InstantiationAwareBeanPostProcessors
//是否有类实现了InstantiationAwareBeanPostProcessor 如果有类实现了就为true
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
// 6.是否需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

PropertyDescriptor[] filteredPds = null;

//重点看这个if代码块,重要程度 5
// 7.注册过InstantiationAwareBeanPostProcessors 或者 需要依赖检查
if (hasInstAwareBpps) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
// 7.1 应用后置处理器InstantiationAwareBeanPostProcessor
//获取所有的beanPostProcessors进行遍历
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//依赖注入过程,@Autowired的支持
// 7.1.1 应用后置处理器InstantiationAwareBeanPostProcessor的方法postProcessProperties,
// 进行属性填充前的再次处理。例子:现在最常用的@Autowire属性注入就是这边注入依赖的bean实例对象
PropertyValues pvsToUse = ibp.postProcessProperties(pvs, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
//老版本用这个完成依赖注入过程,@Autowired的支持
// 7.1.2 应用后置处理器InstantiationAwareBeanPostProcessor的方法postProcessPropertyValues,
// 进行属性填充前的再次处理。例子:现在最常用的@Autowire属性注入就是这边注入依赖的bean实例对象
pvsToUse = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvsToUse == null) {
return;
}
}
pvs = pvsToUse;
}
}
}
if (needsDepCheck) {
if (filteredPds == null) {
filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
}
// 7.2 依赖检查,对应depends-on属性
checkDependencies(beanName, mbd, filteredPds, pvs);
}
//这个方法很鸡肋了,建议不看,是老版本用<property name="username" value="Jack"/>
//标签做依赖注入的代码实现,复杂且无用
if (pvs != null) {
// 8.将所有PropertyValues中的属性填充到bean中
applyPropertyValues(beanName, mbd, bw, pvs);
}
}

处理流程如下:

  1. 根据 hasInstantiationAwareBeanPostProcessors 属性来判断是否需要在注入属性之前给 InstantiationAwareBeanPostProcessors 最后一次改变 bean 的机会,此过程可以控制 Spring 是否继续进行属性填充。
  2. 根据注入类型的不同来判断是根据名称来自动注入(autowireByName())还是根据类型来自动注入(autowireByType()),统一存入到 PropertyValues 中,PropertyValues 用于描述 bean 的属性。
  3. 判断是否需要进行 BeanPostProcessor 和 依赖检测。
  4. 将所有 PropertyValues 中的属性填充到 BeanWrapper 中。

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
30
/**
* Fill in any missing property values with references to
* other beans in this factory if autowire is set to "byName".
* 是根据属性名称完成自动依赖注入的
*/
protected void autowireByName(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
// 1.寻找bw中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
// 2.校验是否存在beanName=propertyName的bean实例或者BeanDefinition
if (containsBean(propertyName)) {
// 3.获取propertyName的bean实例对象
Object bean = getBean(propertyName);
// 4.将属性名和属性值添加到pvs
pvs.add(propertyName, bean);
// 5.注册依赖关系到缓存(beanName依赖propertyName)
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");
}
}
}
}

​ 该方法逻辑很简单,获取该 bean 的非简单属性,什么叫做非简单属性呢?就是类型为对象类型的属性,但是这里并不是将所有的对象类型都都会找到,比如 8 个原始类型,String 类型 ,Number类型、Date类型、URL类型、URI类型等都会被忽略,如下:

unsatisfiedNonSimpleProperties
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
/**
* Return an array of non-simple bean properties that are unsatisfied.
* These are probably unsatisfied references to other beans in the
* factory. Does not include simple properties like primitives or Strings.
* 寻找bw中需要依赖注入的属性
*/
protected String[] unsatisfiedNonSimpleProperties(AbstractBeanDefinition mbd, BeanWrapper bw) {
Set<String> result = new TreeSet<>();
// 1.拿到mdb的属性值
PropertyValues pvs = mbd.getPropertyValues();
// 2.拿到bw的PropertyDescriptors
PropertyDescriptor[] pds = bw.getPropertyDescriptors();
// 3.遍历bw的PropertyDescriptors
for (PropertyDescriptor pd : pds) {
// 4.pd用于写入属性值的方法不为空 && pd不是从依赖性检查中排除的bean属性 && pd不包含在pvs里
// && pd的属性类型不是“简单”属性(基础类型、枚举、Number等)
// 4.1 isSimpleProperty: 判断属性是不是“简单”属性
if (pd.getWriteMethod() != null && !isExcludedFromDependencyCheck(pd) && !pvs.contains(pd.getName()) &&
!BeanUtils.isSimpleProperty(pd.getPropertyType())) {
// 4.2 符合条件,则添加pd的name到result中
result.add(pd.getName());
}
}
//5. 转换为数组返回
return StringUtils.toStringArray(result);
}
isSimpleProperty

检查是否是基本属性

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

public static boolean isSimpleProperty(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
// clazz是简单值类型 || ( clazz是数组 && clazz的组件类型为简单值类型)
// getComponentType:返回数组的组件类型,例如: String[] 返回 String.class,如果是非数组,则返回null
return isSimpleValueType(clazz) || (clazz.isArray() && isSimpleValueType(clazz.getComponentType()));
}

public static boolean isSimpleValueType(Class<?> clazz) {
return (ClassUtils.isPrimitiveOrWrapper(clazz) || clazz.isEnum() ||
CharSequence.class.isAssignableFrom(clazz) ||
Number.class.isAssignableFrom(clazz) ||
Date.class.isAssignableFrom(clazz) ||
URI.class == clazz || URL.class == clazz ||
Locale.class == clazz || Class.class == clazz);
}

// ClassUtils.java
public static boolean isPrimitiveOrWrapper(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
// clazz为基础类型 或者 clazz是基础类型的封装类
return (clazz.isPrimitive() || isPrimitiveWrapper(clazz));
}

public static boolean isPrimitiveWrapper(Class<?> clazz) {
Assert.notNull(clazz, "Class must not be null");
// 检查clazz是否为8种基础类型的包装类
// primitiveWrapperTypeMap缓存包含8种基础类型和包装类的映射,例如:Integer.class -> int.class
return primitiveWrapperTypeMap.containsKey(clazz);
}

static {
primitiveWrapperTypeMap.put(Boolean.class, boolean.class);
primitiveWrapperTypeMap.put(Byte.class, byte.class);
primitiveWrapperTypeMap.put(Character.class, char.class);
primitiveWrapperTypeMap.put(Double.class, double.class);
primitiveWrapperTypeMap.put(Float.class, float.class);
primitiveWrapperTypeMap.put(Integer.class, int.class);
primitiveWrapperTypeMap.put(Long.class, long.class);
primitiveWrapperTypeMap.put(Short.class, short.class);

// ...
}
containsBean

检查是否保包含BeanName

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/**
* 检查是否保包含BeanName
*/
@Override
public boolean containsBean(String name) {
// 1.将name转换为真正的beanName
String beanName = transformedBeanName(name);
// 2.检查singletonObjects缓存和beanDefinitionMap缓存中是否存在beanName
if (containsSingleton(beanName) || containsBeanDefinition(beanName)) {
// 3.name不带&前缀,或者是FactoryBean,则返回true
return (!BeanFactoryUtils.isFactoryDereference(name) || isFactoryBean(name));
}
// Not found -> check parent.
// 4.没有找到则检查parentBeanFactory
BeanFactory parentBeanFactory = getParentBeanFactory();
return (parentBeanFactory != null && parentBeanFactory.containsBean(originalBeanName(name)));
}

registerDependentBean

注册依赖关系到缓存(beanName依赖propertyName)

过滤条件为:有可写方法、依赖检测中没有被忽略、不是简单属性类型。其实这里获取的就是需要依赖注入的属性。

获取需要依赖注入的属性后,通过迭代、递归的方式初始化相关的 bean,然后调用 registerDependentBean() 完成注册依赖,如下:

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
/**
* Register a dependent bean for the given bean,
* to be destroyed before the given bean is destroyed.
* 注册依赖的bean和bean name的映射关系
*
* @param beanName the name of the bean
* @param dependentBeanName the name of the dependent bean
*/
public void registerDependentBean(String beanName, String dependentBeanName) {
// 1.解析别名
String canonicalName = canonicalName(beanName);

synchronized (this.dependentBeanMap) {
//2. 拿到依赖canonicalName的beanName集合
//3.将dependentBeanName添加到依赖canonicalName的beanName集合中
Set<String> dependentBeans =
this.dependentBeanMap.computeIfAbsent(canonicalName, k -> new LinkedHashSet<>(8));
// 5.如果dependentBeans包含dependentBeanName,则表示依赖关系已经存在,直接返回
if (!dependentBeans.add(dependentBeanName)) {
return;
}
}
//4.如果依赖关系还没有注册,则将两者的关系注册到dependentBeanMap和dependenciesForBeanMap缓存
synchronized (this.dependenciesForBeanMap) {
Set<String> dependenciesForBean =
this.dependenciesForBeanMap.computeIfAbsent(dependentBeanName, k -> new LinkedHashSet<>(8));
dependenciesForBean.add(canonicalName);
}
}

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
/**
* Abstract method defining "autowire by type" (bean properties by type) behavior.
* <p>This is like PicoContainer default, in which there must be exactly one bean
* of the property type in the bean factory. This makes bean factories simple to
* configure for small namespaces, but doesn't work as well as standard Spring
* behavior for bigger applications.
* 按类型注入
*/
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {

// 获取 TypeConverter 实例
// 使用自定义的 TypeConverter,用于取代默认的 PropertyEditor 机制
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
//创建BeanName属性名称集合
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
// 1.寻找bw中需要依赖注入的属性
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
// 2.遍历所有需要依赖注入的属性
for (String propertyName : propertyNames) {
try {
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.
if (Object.class != pd.getPropertyType()) {
// 3.获取指定属性的set方法,封装成MethodParameter(必须有set方法才能通过属性来注入)
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
//如果后置处理器有优先级,则不允许eager init进行类型匹配。
boolean eager = !(bw.getWrappedInstance() instanceof PriorityOrdered);
// 4.将MethodParameter的方法参数索引信息封装成DependencyDescriptor
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
// 5.解析当前属性所匹配的bean实例,并把解析到的bean实例的beanName存储在autowiredBeanNames中
// 当属性存在过个封装 bean 时将会找到所有匹配的 bean 并将其注入
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
if (autowiredArgument != null) {
// 6.如果找到了依赖的bean实例,将属性名和bean实例放到pvs中
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
// 7.注册依赖关系,beanName依赖autowiredBeanName
registerDependentBean(autowiredBeanName, beanName);
if (logger.isTraceEnabled()) {
logger.trace("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
//8.清空属性名称集合
autowiredBeanNames.clear();
}
} catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}

applyPropertyValues

将所有PropertyValues中的属性填充到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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
/**
* Apply the given property values, resolving any runtime references
* to other beans in this bean factory. Must use deep copy, so we
* don't permanently modify this property.
* 将所有PropertyValues中的属性填充到bean中
*/
protected void applyPropertyValues(String beanName, BeanDefinition mbd, BeanWrapper bw, PropertyValues pvs) {
if (pvs.isEmpty()) {
return;
}

if (System.getSecurityManager() != null && bw instanceof BeanWrapperImpl) {
((BeanWrapperImpl) bw).setSecurityContext(getAccessControlContext());
}

// MutablePropertyValues 类型属性
MutablePropertyValues mpvs = null;
// 原始类型
List<PropertyValue> original;
// 1.获取属性值列表
if (pvs instanceof MutablePropertyValues) {
mpvs = (MutablePropertyValues) pvs;
// 1.1 如果mpvs中的值已经被转换为对应的类型,那么可以直接设置到BeanWrapper中
if (mpvs.isConverted()) {
// Shortcut: use the pre-converted values as-is.
try {
// 设置到 BeanWrapper 中去
bw.setPropertyValues(mpvs);
return;
} catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}
original = mpvs.getPropertyValueList();
} else {
// 1.2 如果pvs并不是使用MutablePropertyValues封装的类型,那么直接使用原始的属性获取方法
original = Arrays.asList(pvs.getPropertyValues());
}

TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
// 2.1 获取对应的解析器
BeanDefinitionValueResolver valueResolver = new BeanDefinitionValueResolver(this, beanName, mbd, converter);

// Create a deep copy, resolving any references for values.
// 2.2 创建深层拷贝副本,用于存放解析后的属性值
List<PropertyValue> deepCopy = new ArrayList<>(original.size());
boolean resolveNecessary = false;
// 3.遍历属性,将属性转换为对应类的对应属性的类型
for (PropertyValue pv : original) {
if (pv.isConverted()) {
// 3.1 如果pv已经包含转换的值,则直接添加到deepCopy
deepCopy.add(pv);
} else {
// 3.2 否则,进行转换
// 3.2.1 拿到pv的原始属性名和属性值
String propertyName = pv.getName();
Object originalValue = pv.getValue();
if (originalValue == AutowiredPropertyMarker.INSTANCE) {
Method writeMethod = bw.getPropertyDescriptor(propertyName).getWriteMethod();
if (writeMethod == null) {
throw new IllegalArgumentException("Autowire marker for property without write method: " + pv);
}
originalValue = new DependencyDescriptor(new MethodParameter(writeMethod, 0), true);
}
// 3.2.2 使用解析器解析原始属性值
Object resolvedValue = valueResolver.resolveValueIfNecessary(pv, originalValue);
Object convertedValue = resolvedValue;
// 3.2.3 判断该属性是否可转换
boolean convertible = bw.isWritableProperty(propertyName) &&
!PropertyAccessorUtils.isNestedOrIndexedProperty(propertyName);
if (convertible) {
// 3.2.4 如果可转换,则转换指定目标属性的给定值
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.
// 3.2.5 在合并的BeanDefinition中存储转换后的值,以避免为每个创建的bean实例重新转换
if (resolvedValue == originalValue) {
if (convertible) {
pv.setConvertedValue(convertedValue);
}
deepCopy.add(pv);
} else if (convertible && originalValue instanceof TypedStringValue &&
!((TypedStringValue) originalValue).isDynamic() &&
!(convertedValue instanceof Collection || ObjectUtils.isArray(convertedValue))) {
pv.setConvertedValue(convertedValue);
deepCopy.add(pv);
} else {
resolveNecessary = true;
deepCopy.add(new PropertyValue(pv, convertedValue));
}
}
}
if (mpvs != null && !resolveNecessary) {
mpvs.setConverted();
}

// Set our (possibly massaged) deep copy.
try {
// 4.设置bean的属性值为deepCopy
bw.setPropertyValues(new MutablePropertyValues(deepCopy));
} catch (BeansException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Error setting property values", ex);
}
}

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
38
39
40
41
42
43
/**
* Initialize the given bean instance, applying factory callbacks
* as well as init methods and bean post processors.
* <p>Called from {@link #createBean} for traditionally defined beans,
* and from {@link #initializeBean} for existing bean instances.
* <p>
* 实例化bean结束后的一些初始化操作 调用bean的一些初始化接口
*/
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
// 1.激活Aware方法
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
} else {
//1.1 调用Aware方法
invokeAwareMethods(beanName, bean);
}

Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
// 2.在初始化前应用BeanPostProcessor的postProcessBeforeInitialization方法,允许对bean实例进行包装
//对类中某些特殊方法的调用,比如@PostConstruct,Aware接口,非常重要 重要程度 :5
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}

try {
// 3.调用初始化方法
//InitializingBean接口,afterPropertiesSet,init-method属性调用,非常重要,重要程度:5
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()) {
// 4.在初始化后应用BeanPostProcessor的postProcessAfterInitialization方法,允许对bean实例进行包装
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
// 5.返回wrappedBean
return wrappedBean;
}

invokeAwareMethods

调用Aware方法,完成实例化后的一些初始化工作

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
/**
* 调用Aware方法
*
* @param beanName
* @param bean
*/
private void invokeAwareMethods(final String beanName, final Object bean) {
//如果bean实现了Aware接口
// BeanNameAware: 实现此接口的类想要拿到beanName,因此我们在这边赋值给它
if (bean instanceof Aware) {
//如果实现了BeanNameAware接口
if (bean instanceof BeanNameAware) {
//进行初始化beanName
((BeanNameAware) bean).setBeanName(beanName);
}
//如果实现了BeanClassLoaderAware接口
// BeanClassLoaderAware:实现此接口的类想要拿到beanClassLoader,因此我们在这边赋值给它
if (bean instanceof BeanClassLoaderAware) {
ClassLoader bcl = getBeanClassLoader();
if (bcl != null) {
//设置bean的classLoader
((BeanClassLoaderAware) bean).setBeanClassLoader(bcl);
}
}
//如果实现了BeanFactoryAware接口
// BeanFactoryAware: 实现此接口的类想要拿到 BeanFactory,因此我们在这边赋值给它
if (bean instanceof BeanFactoryAware) {
//设置抽象工厂类
((BeanFactoryAware) bean).setBeanFactory(AbstractAutowireCapableBeanFactory.this);
}
}
}

​ 如果对 Spring 比较熟悉的同学应该知道,以 Aware 为结尾的类都是一些扩展接口,用于提供给开发者获取到 BeanFactory 中的一些属性或对象。

applyBeanPostProcessorsBeforeInitialization

对类中某些特殊方法的调用,比如@PostConstruct,Aware接口,非常重要

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
/**
* 调用BeanPostProcessor的postProcessBeforeInitialization接口
* 对类中某些特殊方法的调用,比如@PostConstruct,Aware接口,非常重要
*/
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {

Object result = existingBean;
/*
* 着重看几个
* 1、ApplicationContextAwareProcessor 对某个Aware接口方法的调用
* 2、InitDestroyAnnotationBeanPostProcessor @PostConstruct注解方法的调用
*
* 3、ImportAwareBeanPostProcessor 对ImportAware类型实例setImportMetadata调用
* 这个对理解springboot有很大帮助。 这里暂时不需要深入看
* */
// 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessBeforeInitialization方法
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// 2.在bean初始化方法执行前,调用postProcessBeforeInitialization方法
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}

后面会对里面的一些详细的类进行讲解

invokeInitMethods

实例化bean后调用InitMethod接口进行初始化

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
/**
* Give a bean a chance to react now all its properties are set,
* and a chance to know about its owning bean factory (this object).
* This means checking whether the bean implements InitializingBean or defines
* a custom init method, and invoking the necessary callback(s) if it does.
* 实例化bean后调用InitMethod接口进行初始化
*
*/
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {

// 1.首先检查bean是否实现了InitializingBean接口,如果是的话调用afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
// 2.调用afterPropertiesSet方法
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 {
//2.1 调用初始化bean的afterPropertiesSet方法
((InitializingBean) bean).afterPropertiesSet();
}
}
//3. 调用initMethod方法
if (mbd != null && bean.getClass() != NullBean.class) {
//3.1 获取initMethod方法
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//3.2 调用自定义的InitMethod方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
invokeCustomInitMethod

调用自定义的InitMethod方法

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

/**
* Invoke the specified custom init method on the given bean.
* Called by invokeInitMethods.
* <p>Can be overridden in subclasses for custom resolution of init
* methods with arguments.
* <p>
* 调用自定义的InitMethod方法
*/
protected void invokeCustomInitMethod(String beanName, final Object bean, RootBeanDefinition mbd)
throws Throwable {
//1. 获取初始化方法名称
String initMethodName = mbd.getInitMethodName();
Assert.state(initMethodName != null, "No init method set");
//2. 获取initmethod的反射对象
Method initMethod = (mbd.isNonPublicAccessAllowed() ?
BeanUtils.findMethod(bean.getClass(), initMethodName) :
ClassUtils.getMethodIfAvailable(bean.getClass(), initMethodName));

// 3.如果不存在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 + "'");
}
//4. 如果存在接口方法就获取接口方法
Method methodToInvoke = ClassUtils.getInterfaceMethodIfPossible(initMethod);
// 5. 用初始化方法
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);
//调用initMetod方法
methodToInvoke.invoke(bean);
} catch (InvocationTargetException ex) {
throw ex.getTargetException();
}
}
}

applyBeanPostProcessorsAfterInitialization

执行BeanPostProcessor的postProcessAfterInitialization接口

完成初始化后的一些调用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/**
* 是一个扩展点
* 执行BeanPostProcessor的postProcessAfterInitialization接口
*/
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
// 1.遍历所有注册的BeanPostProcessor实现类,调用postProcessAfterInitialization方法
for (BeanPostProcessor processor : getBeanPostProcessors()) {
// 2.在bean初始化后,调用postProcessAfterInitialization方法
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
// 3.如果返回null,则不会调用后续的BeanPostProcessors
return result;
}
result = current;
}
return result;
}

registerDisposableBeanIfNecessary

注册bean销毁时的类DisposableBeanAdapter

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
/**
* Add the given bean to the list of disposable beans in this factory,
* registering its DisposableBean interface and/or the given destroy method
* to be called on factory shutdown (if applicable). Only applies to singletons.
* 注册销毁的bean
*/
protected void registerDisposableBeanIfNecessary(String beanName, Object bean, RootBeanDefinition mbd) {
AccessControlContext acc = (System.getSecurityManager() != null ? getAccessControlContext() : null);
// 1.mbd的scope不是prototype && 给定的bean需要在关闭时销毁
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.
// 2.单例模式下注册用于销毁的bean到disposableBeans缓存,执行给定bean的所有销毁工作:
// DestructionAwareBeanPostProcessors,DisposableBean接口,自定义销毁方法
// 2.1 DisposableBeanAdapter:使用DisposableBeanAdapter来封装用于销毁的bean
//注册对应bean的销毁的DisposableBeanAdapter
registerDisposableBean(beanName,
new DisposableBeanAdapter(bean, beanName, mbd, getBeanPostProcessors(), acc));
} else {
// A bean with a custom scope...
// 3.自定义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));
}
}
}

requiresDestruction

判断给定的 bean 是否需要在关闭时销毁

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* Determine whether the given bean requires destruction on shutdown.
* <p>The default implementation checks the DisposableBean interface as well as
* a specified destroy method and registered DestructionAwareBeanPostProcessors.
* 判断给定的 bean 是否需要在关闭时销毁
*/
protected boolean requiresDestruction(Object bean, RootBeanDefinition mbd) {
// 1.DisposableBeanAdapter.hasDestroyMethod(bean, mbd):判断bean是否有destroy方法
// 2.hasDestructionAwareBeanPostProcessors():判断当前BeanFactory是否注册过DestructionAwareBeanPostProcessor
// 3.DisposableBeanAdapter.hasApplicableProcessors:是否存在适用于bean的DestructionAwareBeanPostProcessor
return (bean.getClass() != NullBean.class &&
(DisposableBeanAdapter.hasDestroyMethod(bean, mbd) || (hasDestructionAwareBeanPostProcessors() &&
DisposableBeanAdapter.hasApplicableProcessors(bean, getBeanPostProcessors()))));
}
hasDestroyMethod

判断 bean 是否有 destroy 方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Check whether the given bean has any kind of destroy method to call.
* 判断 bean 是否有 destroy 方法
*/
public static boolean hasDestroyMethod(Object bean, RootBeanDefinition beanDefinition) {
if (bean instanceof DisposableBean || bean instanceof AutoCloseable) {
// 1.如果bean实现了DisposableBean接口 或者 bean是AutoCloseable实例,则返回true
return true;
}
// 2.拿到bean自定义的destroy方法名
String destroyMethodName = beanDefinition.getDestroyMethodName();
if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName)) {
// 3.如果自定义的destroy方法名为“(inferred)”(该名字代表需要我们自己去推测destroy的方法名),
// 则检查该bean是否存在方法名为“close”或“shutdown”的方法,如果存在,则返回true
return (ClassUtils.hasMethod(bean.getClass(), CLOSE_METHOD_NAME) ||
ClassUtils.hasMethod(bean.getClass(), SHUTDOWN_METHOD_NAME));
}
// 4.如果destroyMethodName不为空,则返回true
return StringUtils.hasLength(destroyMethodName);
}
hasApplicableProcessors

是否存在适用于 bean 的 DestructionAwareBeanPostProcessor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Check whether the given bean has destruction-aware post-processors applying to it.
* 是否存在适用于 bean 的 DestructionAwareBeanPostProcessor
*/
public static boolean hasApplicableProcessors(Object bean, List<BeanPostProcessor> postProcessors) {
if (!CollectionUtils.isEmpty(postProcessors)) {
// 1.遍历所有的BeanPostProcessor
for (BeanPostProcessor processor : postProcessors) {
// 2.如果processor是DestructionAwareBeanPostProcessor
if (processor instanceof DestructionAwareBeanPostProcessor) {
DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
if (dabpp.requiresDestruction(bean)) {
// 3.如果给定的bean实例需要通过此后处理器进行销毁,则返回true
return true;
}
}
}
}
return false;
}

DisposableBeanAdapter

创建一个新的DisposableBeanAdapter

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
/**
* Create a new DisposableBeanAdapter for the given bean.
* 创建一个新的DisposableBeanAdapter
*/
public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition beanDefinition,
List<BeanPostProcessor> postProcessors, @Nullable AccessControlContext acc) {

Assert.notNull(bean, "Disposable bean must not be null");
this.bean = bean;
this.beanName = beanName;
//如果bean实现了DisposableBean接口
// 1.判断bean是否需要调用DisposableBean的destroy方法
this.invokeDisposableBean =
(this.bean instanceof DisposableBean && !beanDefinition.isExternallyManagedDestroyMethod("destroy"));
this.nonPublicAccessAllowed = beanDefinition.isNonPublicAccessAllowed();
this.acc = acc;
// 2.拿到自定义的destroy方法名
String destroyMethodName = inferDestroyMethodIfNecessary(bean, beanDefinition);
if (destroyMethodName != null && !(this.invokeDisposableBean && "destroy".equals(destroyMethodName)) &&
!beanDefinition.isExternallyManagedDestroyMethod(destroyMethodName)) {
this.destroyMethodName = destroyMethodName;
// 3.拿到自定义的destroy方法,赋值给this.destroyMethod
Method destroyMethod = determineDestroyMethod(destroyMethodName);
if (destroyMethod == null) {
if (beanDefinition.isEnforceDestroyMethod()) {
// 4.如果destroy方法名为空,并且enforceDestroyMethod为true,则抛出异常
throw new BeanDefinitionValidationException("Could not find a destroy method named '" +
destroyMethodName + "' on bean with name '" + beanName + "'");
}
} else {
// 5.拿到destroy方法的参数类型数组
//获取销毁方法的参数
Class<?>[] paramTypes = destroyMethod.getParameterTypes();
//如果参数>1 直接报错
// 6.如果destroy方法的参数大于1个,则抛出异常
if (paramTypes.length > 1) {
throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
beanName + "' has more than one parameter - not supported as destroy method");
//如果有一个参数 并且不是boolean类型 直接报错
// 7.如果destroy方法的参数为1个,并且该参数的类型不为boolean,则抛出异常
} else if (paramTypes.length == 1 && boolean.class != paramTypes[0]) {
throw new BeanDefinitionValidationException("Method '" + destroyMethodName + "' of bean '" +
beanName + "' has a non-boolean parameter - not supported as destroy method");
}
//8. 获取该方法的接口方法
destroyMethod = ClassUtils.getInterfaceMethodIfPossible(destroyMethod);
}
//9. 设置到全局的destroyMethod
this.destroyMethod = destroyMethod;
}
//10. 找到支持@Destroy注解的postProcessors
this.beanPostProcessors = filterPostProcessors(postProcessors, bean);
}

inferDestroyMethodIfNecessary

获取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
/**
* 获取bean的销毁方法
*/
@Nullable
private String inferDestroyMethodIfNecessary(Object bean, RootBeanDefinition beanDefinition) {
//1. 从beanDefinition中获取销毁方法
String destroyMethodName = beanDefinition.getDestroyMethodName();
// 2.如果destroy方法名为“(inferred)”|| destroyMethodName为null,并且bean是AutoCloseable实例
//如果destroyMethodName是INFER_METHOD或者为null并且实现了AutoCloseable
if (AbstractBeanDefinition.INFER_METHOD.equals(destroyMethodName) ||
(destroyMethodName == null && bean instanceof AutoCloseable)) {
// Only perform destroy method inference or Closeable detection
// in case of the bean not explicitly implementing DisposableBean
// 3.如果bean没有实现DisposableBean接口,则尝试推测destroy方法的名字
//如果没有实现DisposableBean接口
if (!(bean instanceof DisposableBean)) {
try {
// 4.尝试在bean中寻找方法名为close的方法作为destroy方法
return bean.getClass().getMethod(CLOSE_METHOD_NAME).getName();
} catch (NoSuchMethodException ex) {
try {
// 5.尝试在bean中寻找方法名为close的方法作为shutdown方法
return bean.getClass().getMethod(SHUTDOWN_METHOD_NAME).getName();
} catch (NoSuchMethodException ex2) {
// no candidate destroy method found
}
}
}
return null;
}
//6. 其他清空返回destroyMethodName方法
return (StringUtils.hasLength(destroyMethodName) ? destroyMethodName : null);
}
filterPostProcessors

找到所有类型是DestructionAwareBeanPostProcessor的BeanPostProcessor 加入到filteredPostProcessors并返回

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
/**
* Search for all DestructionAwareBeanPostProcessors in the List.
* 找到支持@Destroy注解的postProcessors
* 找到所有类型是DestructionAwareBeanPostProcessor的BeanPostProcessor 加入到filteredPostProcessors并返回
*/
@Nullable
private List<DestructionAwareBeanPostProcessor> filterPostProcessors(List<BeanPostProcessor> processors, Object bean) {
List<DestructionAwareBeanPostProcessor> filteredPostProcessors = null;
if (!CollectionUtils.isEmpty(processors)) {
filteredPostProcessors = new ArrayList<>(processors.size());
//1. 遍历所有的processors
for (BeanPostProcessor processor : processors) {
//2. 如果实现了DestructionAwareBeanPostProcessor接口
if (processor instanceof DestructionAwareBeanPostProcessor) {
DestructionAwareBeanPostProcessor dabpp = (DestructionAwareBeanPostProcessor) processor;
//2.1 检查dabpp是否实现了对应bean的@Destroy注解的支持
if (dabpp.requiresDestruction(bean)) {
//2.2 如果给定的bean实例需要通过此后处理器进行销毁,则添加到filteredPostProcessors
filteredPostProcessors.add(dabpp);
}
}
}
}
return filteredPostProcessors;
}

总结

​ 至此,finishBeanFactoryInitialization 方法解析完毕,文章来介绍 finishBeanFactoryInitialization 方法。在 finishBeanFactoryInitialization 方法中,我们主要做了以下操作:

  • 将之前解析的 BeanDefinition 进一步处理,将有父 BeanDefinition 的进行合并,获得 MergedBeanDefinition

  • 尝试从缓存获取 bean 实例

  • 处理特殊的 bean —— FactoryBean 的创建

  • 创建 bean 实例

  • 循环引用的处理

  • bean 实例属性填充

  • bean 实例的初始化

  • BeanPostProcessor 的各种扩展应用

​ finishBeanFactoryInitialization 方法解析的结束,也标志着 Spring IoC 整个构建过程中,重要的内容基本都已经解析完毕。由于工程较为浩大,因此整个系列的文章中,肯定会有各种各样的问题:理解错误的、用词不一致的(有时候用 “BeanDefinition”,有时候用 “bean 定义”)、漏掉的等等,后续如果有时间,可能会在抽空完善一下,尽量减少出现的问题,也欢迎各位同学指正文章中的错误。

​ 另外,本系列文章到目前为止都是单纯的解析 Spring IoC 的源码,之后可能会再补充一些重要的内容,例如:本文提到要写的@Autowire 注解的依赖注入过程、Spring IoC 中的核心类的介绍等。

评论