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

Spring源码分析-createBean&无参构造方式实例化

前言

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

流程图

createBean

创建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
/**
* Central method of this class: creates a bean instance,
* populates the bean instance, applies post-processors, etc.
* <p>
* 创建bean的核心方法
*
* @see #doCreateBean
*/
@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.
// 1.解析beanName对应的Bean的类型,例如:com.test.spring.dao.UserDao
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
// 如果resolvedClass存在,并且mdb的beanClass类型不是Class,并且mdb的beanClass不为空(则代表beanClass存的是Class的name),
// 则使用mdb深拷贝一个新的RootBeanDefinition副本,并且将解析的Class赋值给拷贝的RootBeanDefinition副本的beanClass属性,
// 该拷贝副本取代mdb用于后续的操作
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}

// Prepare method overrides.
try {
// 2.验证及准备覆盖的方法(对override属性进行标记及验证)
//进行MethodOverride容器的检测以及设置
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.
// 3.实例化前的处理,给InstantiationAwareBeanPostProcessor一个机会返回代理对象来替代真正的bean实例,达到“短路”效果
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
// 4.如果bean不为空,则会跳过Spring默认的实例化过程,直接使用返回的bean
if (bean != null) {
return bean;
}
} catch (Throwable ex) {
throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
"BeanPostProcessor before instantiation of bean failed", ex);
}

try {
// 5.创建Bean实例(真正创建Bean的方法)
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isTraceEnabled()) {
logger.trace("Finished creating instance of bean '" + beanName + "'");
}
// 6.返回创建的Bean实例
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);
}
}

resolveBeforeInstantiation

实例化前的处理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@Nullable
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
Object bean = null;
// 1.mbd不是合成的,并且BeanFactory中存在InstantiationAwareBeanPostProcessor
if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
// Make sure bean class is actually resolved at this point.
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
// 2.解析beanName对应的Bean实例的类型
Class<?> targetType = determineTargetType(beanName, mbd);
if (targetType != null) {
// 3.实例化前的后置处理器应用(处理InstantiationAwareBeanPostProcessor)
bean = applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
if (bean != null) {
// 4.如果返回的bean不为空,会跳过Spring默认的实例化过程,
// 所以只能在这里调用BeanPostProcessor实现类的postProcessAfterInitialization方法
bean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
}
}
}
// 5.如果bean不为空,则将beforeInstantiationResolved赋值为true,代表在实例化之前已经解析
mbd.beforeInstantiationResolved = (bean != null);
}
return bean;
}
applyBeanPostProcessorsBeforeInstantiation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Nullable
protected Object applyBeanPostProcessorsBeforeInstantiation(Class<?> beanClass, String beanName) {
// 1.遍历当前BeanFactory中的BeanPostProcessor
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 2.应用InstantiationAwareBeanPostProcessor后置处理器,允许postProcessBeforeInstantiation方法返回bean对象的代理
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
// 3.执行postProcessBeforeInstantiation方法,在Bean实例化前操作,
// 该方法可以返回一个构造完成的Bean实例,从而不会继续执行创建Bean实例的“正规的流程”,达到“短路”的效果
Object result = ibp.postProcessBeforeInstantiation(beanClass, beanName);
if (result != null) {
// 4.如果result不为空,也就是有后置处理器返回了bean实例对象,则会跳过Spring默认的实例化过程
return result;
}
}
}
return null;
}

​ 在实例化之前执行 InstantiationAwareBeanPostProcessor 的 postProcessBeforeInstantiation 方法,该方法可以返回 bean 实例的代理,从而跳过 Spring 默认的实例化过程。

doCreateBean

真正创建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
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
/**
* Actually create the specified bean. Pre-creation processing has already happened
* at this point, e.g. checking {@code postProcessBeforeInstantiation} callbacks.
* <p>Differentiates between default bean instantiation, use of a
* factory method, and autowiring a constructor.
* 真实的开始创建bean的实例
* 主要更能
* 1、创建bean的实例
* 2、对各种注解进行装配
* 3、实现依赖注入
*
*/
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {

// Instantiate the bean.
// 1.新建Bean包装类,封装了bean的实例
BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
// 2.如果是FactoryBean,则需要先移除未完成的FactoryBean实例的缓存
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
//重要程度 5
// 3.根据beanName、mbd、args,使用对应的策略创建Bean实例,并返回包装类BeanWrapper
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
// 4.拿到创建好的Bean实例
final Object bean = instanceWrapper.getWrappedInstance();
// 5.拿到Bean实例的类型
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 {
//CommonAnnotationBeanPostProcessor 支持了@PostConstruct,@PreDestroy,@Resource注解
//AutowiredAnnotationBeanPostProcessor 支持 @Autowired,@Value注解
//BeanPostProcessor接口的典型运用,这里要理解这个接口
// 6.应用后置处理器MergedBeanDefinitionPostProcessor,允许修改MergedBeanDefinition,
// Autowired注解正是通过此方法实现注入类型的预解析
//重要程度5,必须看
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提前暴露
// 7.判断是否需要提早曝光实例:单例 && 允许循环依赖 && 当前bean正在创建中
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
//beanName是否正在创建
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
if (logger.isTraceEnabled()) {
logger.trace("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
// 8.提前曝光beanName的ObjectFactory,用于解决循环引用
//这里着重理解,对理解循环依赖帮助非常大,重要程度 5 添加三级缓存
// 8.1 应用后置处理器SmartInstantiationAwareBeanPostProcessor,允许返回指定bean的早期引用,若没有则直接返回bean
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}

// Initialize the bean instance.
Object exposedObject = bean;
try {
// 9.对bean进行属性填充;其中,可能存在依赖于其他bean的属性,则会递归初始化依赖的bean实例
//ioc di,依赖注入的核心方法,该方法必须看,重要程度:5
populateBean(beanName, mbd, instanceWrapper);

// 10.对bean进行初始化
//bean 实例化+ioc依赖注入完以后的调用,非常重要,重要程度:5
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);
}
}

// 11.如果允许提前曝光实例,则进行循环依赖检查
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
// 11.1 earlySingletonReference只有在当前解析的bean存在循环依赖的情况下才会不为空
if (earlySingletonReference != null) {
if (exposedObject == bean) {
// 11.2 如果exposedObject没有在initializeBean方法中被增强,则不影响之前的循环引用
exposedObject = earlySingletonReference;

// 11.3 如果exposedObject在initializeBean方法中被增强 && 不允许在循环引用的情况下使用注入原始bean实例
// && 当前bean有被其他bean依赖
} else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
// 11.4 拿到依赖当前bean的所有bean的beanName数组
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
for (String dependentBean : dependentBeans) {
// 11.5 尝试移除这些bean的实例,因为这些bean依赖的bean已经被增强了,他们依赖的bean相当于脏数据
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
// 11.6 移除失败的添加到 actualDependentBeans
actualDependentBeans.add(dependentBean);
}
}
if (!actualDependentBeans.isEmpty()) {
// 11.7 如果存在移除失败的,则抛出异常,因为存在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 {
// 12.注册用于销毁的bean,执行销毁操作的有三种:自定义destroy方法、DisposableBean接口、DestructionAwareBeanPostProcessor
//注册bean销毁时的类DisposableBeanAdapter
registerDisposableBeanIfNecessary(beanName, bean, mbd);
} catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
// 13.完成创建并返回
return exposedObject;
}

真正创建 bean 实例的方法,整个系列文章中的核心中的核心,很多代码是前后相关联的,需要反复阅读才能很好的理解。

11.1 earlySingletonReference 只有在当前解析的 bean 存在循环依赖的情况下才会不为空。

​ 因为如果不是循环依赖,只会在完全创建完 bean 实例才会添加到 singletonObjects 缓存。此时,我们正在创建 bean 的过程中,还没有完全创建完,singletonObjects 缓存是肯定没有当前 beanName 的;而如果不存在循环引用,从 doGetBean 方法开始,getSingleton 方法只会在最初 doGetBean 方法里调用一次,不存在循环引用,也就用不到提前曝光的 ObjectFactory 来创建 bean 对象,从而 earlySingletonObjects 缓存肯定也是没有 beanName 的 bean 实例对象的,所以必然返回空。

12.注册用于销毁的 bean,执行销毁操作的有三种:自定义 destroy 方法、DisposableBean 接口、DestructionAwareBeanPostProcessor。

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
79
80
/**
* Create a new instance for the specified bean, using an appropriate instantiation strategy:
* factory method, constructor autowiring, or simple instantiation.
* 创建一个bean的实例 首先factory method的方式,然后选择构造方法创建最后无参创建
*/
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
// Make sure bean class is actually resolved at this point.
//反射拿到Class对象,解析bean的类型信息
Class<?> beanClass = resolveBeanClass(mbd, beanName);

// beanClass不为空 && beanClass不是公开类(不是public修饰) && 该bean不允许访问非公共构造函数和方法,则抛异常
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());
}

//1. 如果存在supplier回调,则使用给定的回调方法初始化策略
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}

// 2.如果存在工厂方法则使用工厂方法实例化bean对象
//如果有FactoryMethodName属性
if (mbd.getFactoryMethodName() != null) {
//使用FactoryMethod实例化bean
return instantiateUsingFactoryMethod(beanName, mbd, args);
}

// Shortcut when re-creating the same bean...
// resolved: 构造函数或工厂方法是否已经解析过
boolean resolved = false;
// autowireNecessary: 是否需要自动注入(即是否需要解析构造函数参数)
boolean autowireNecessary = false;
if (args == null) {
// 3.加锁
synchronized (mbd.constructorArgumentLock) {
if (mbd.resolvedConstructorOrFactoryMethod != null) {
// 3.1 如果resolvedConstructorOrFactoryMethod缓存不为空,则将resolved标记为已解析
resolved = true;
// 3.2 根据constructorArgumentsResolved判断是否需要自动注入
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
if (resolved) {
// 4.如果已经解析过,则使用resolvedConstructorOrFactoryMethod缓存里解析好的构造函数方法
if (autowireNecessary) {
// 4.1 需要自动注入,则执行构造函数自动注入
return autowireConstructor(beanName, mbd, null, null);
} else {
// 4.2 否则使用默认的构造函数进行bean的实例化
return instantiateBean(beanName, mbd);
}
}

// Candidate constructors for autowiring?
// 5.应用后置处理器SmartInstantiationAwareBeanPostProcessor,拿到bean的候选构造函数
/**
* 寻找当前正在实例化的bean中有@Autowired注解的构造函数
* 拿到当前beanClass的构造器可能存在多个包含@Autowired的构造方法
*/
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
// 6. 如果ctors不为空 || mbd的注入方式为AUTOWIRE_CONSTRUCTOR || mdb定义了构造函数的参数值 || args不为空,则执行构造函数自动注入
//如果ctors不为空,就说明构造函数上有@Autowired注解
return autowireConstructor(beanName, mbd, ctors, args);
}
//7. 获取偏好的构造方法
// Preferred constructors for default construction?
ctors = mbd.getPreferredConstructors();
if (ctors != null) {
//7.1 使用偏好的构造方法实例bean
return autowireConstructor(beanName, mbd, ctors, null);
}
//8. 无参构造函数的实例化,大部分的实例是采用的无参构造函数的方式实例化
// No special handling: simply use no-arg constructor.
return instantiateBean(beanName, mbd);
}

实例化 bean 是一个复杂的过程,其主要的逻辑为:

  • 如果存在 Supplier 回调,则调用 obtainFromSupplier() 进行初始化
  • 如果存在工厂方法,则使用工厂方法进行初始化
  • 首先判断缓存,如果缓存中存在,即已经解析过了,则直接使用已经解析了的,根据 constructorArgumentsResolved 参数来判断是使用构造函数自动注入还是默认构造函数
  • 如果缓存中没有,则需要先确定到底使用哪个构造函数来完成解析工作,因为一个类有多个构造函数,每个构造函数都有不同的构造参数,所以需要根据参数来锁定构造函数并完成初始化,如果存在参数则使用相应的带有参数的构造函数,否则使用默认构造函数。
obtainFromSupplier
1
2
3
4
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}

​ 首先从 BeanDefinition 中获取 Supplier,如果不为空,则调用 obtainFromSupplier() 。那么 Supplier 是什么呢?在这之前也没有提到过这个字段。

1
2
3
public interface Supplier<T> {
T get();
}

​ Supplier 接口仅有一个功能性的 get(),该方法会返回一个 T 类型的对象,有点儿类似工厂方法。这个接口有什么作用?用于指定创建 bean 的回调,如果我们设置了这样的回调,那么其他的构造器或者工厂方法都会没有用。在什么设置该参数呢?Spring 提供了相应的 setter 方法,如下:

1
2
3
public void setInstanceSupplier(@Nullable Supplier<?> instanceSupplier) {
this.instanceSupplier = instanceSupplier;
}

​ 在构造 BeanDefinition 的时候设置了该值,如下(以 RootBeanDefinition 为例):

1
2
3
4
5
6
public <T> RootBeanDefinition(@Nullable Class<T> beanClass, String scope, @Nullable Supplier<T> instanceSupplier) {
super();
setBeanClass(beanClass);
setScope(scope);
setInstanceSupplier(instanceSupplier);
}

如果设置了 instanceSupplier 则调用 obtainFromSupplier() 完成 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
protected BeanWrapper obtainFromSupplier(Supplier<?> instanceSupplier, String beanName) {
Object instance;
//1. 从ThreadLocal中获取上一次设置的BeanName
String outerBean = this.currentlyCreatedBean.get();
//2. 设置ThreadLocal为当前的beanName
this.currentlyCreatedBean.set(beanName);
try {
//3. 调用 Supplier 的 get(),返回一个对象
instance = instanceSupplier.get();
} finally {
//3.1 如果outerBean不为空则继续设置outerBean
if (outerBean != null) {
this.currentlyCreatedBean.set(outerBean);
} else {
//3.2 否则从ThreadLocal中删除
this.currentlyCreatedBean.remove();
}
}
//4. 如果返回的实例为空,包装成NullBean
if (instance == null) {
instance = new NullBean();
}
//5. 包装成BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(instance);
//6. 初始化BeanWrapper
initBeanWrapper(bw);
//7. 返回BeanWrapper
return bw;
}

​ 代码很简单,调用 调用 Supplier 的 get() 方法,获得一个 bean 实例对象,然后根据该实例对象构造一个 BeanWrapper 对象 bw,最后初始化该对象。有关于 BeanWrapper 后面专门出文讲解。

determineConstructorsFromBeanPostProcessors
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
/**
* 通过BeanPostProcessor来获取构造方法
* 所有实现了 继承了 SmartInstantiationAwareBeanPostProcessor 的类都会调用,通过埋点的方式来做到代码的通用
* 这里面只有AutowiredAnnotationBeanPostProcessor关注determineCandidateConstructors这个点
* AutowiredAnnotationBeanPostProcessor是在注册context-scan标签的registerAnnotationConfigProcessors方法注册进去的
* 在registerBeanPostProcessors注册BeanPostProcessors的时候实例化的
*/
@Nullable
protected Constructor<?>[] determineConstructorsFromBeanPostProcessors(@Nullable Class<?> beanClass, String beanName)
throws BeansException {
//beanClass不为空并且hasInstantiationAwareBeanPostProcessors属性为true
if (beanClass != null && hasInstantiationAwareBeanPostProcessors()) {
//1. 拿到所有的beanPostProcessor并进行遍历
for (BeanPostProcessor bp : getBeanPostProcessors()) {
//2. 判断是否是SmartInstantiationAwareBeanPostProcessor类型
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
//转换为SmartInstantiationAwareBeanPostProcessor类型
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 3.调用SmartInstantiationAwareBeanPostProcessor的determineCandidateConstructors方法,
// 该方法可以返回要用于beanClass的候选构造函数
// 例如:使用@Autowire注解修饰构造函数,则该构造函数在这边会被AutowiredAnnotationBeanPostProcessor找到
Constructor<?>[] ctors = ibp.determineCandidateConstructors(beanClass, beanName);
if (ctors != null) {
// 4.如果ctors不为空,则不再继续执行其他的SmartInstantiationAwareBeanPostProcessor
return ctors;
}
}
}
}
return null;
}

​ 调用 SmartInstantiationAwareBeanPostProcessor 的 determineCandidateConstructors 方法,该方法可以返回要用于 beanClass 的候选构造函数。使用 @Autowire 注解修饰构造函数,则该构造函数在这边会被 AutowiredAnnotationBeanPostProcessor 找到,该内容会在之后介绍 @Autowire 的文章中单独介绍。

applyMergedBeanDefinitionPostProcessors

对postProcessMergedBeanDefinition进行依赖注解的搜集

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/**
* Apply MergedBeanDefinitionPostProcessors to the specified bean definition,
* invoking their {@code postProcessMergedBeanDefinition} methods.
* <p>
* CommonAnnotationBeanPostProcessor 支持了@PostConstruct@PreDestroy,@Resource注解
* AutowiredAnnotationBeanPostProcessor 支持 @Autowired,@Value注解
* BeanPostProcessor接口的典型运用,这里要理解这个接口
*/
protected void applyMergedBeanDefinitionPostProcessors(RootBeanDefinition mbd, Class<?> beanType, String beanName) {
// 1.获取BeanFactory中已注册的BeanPostProcessor进行遍历
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof MergedBeanDefinitionPostProcessor) {
MergedBeanDefinitionPostProcessor bdp = (MergedBeanDefinitionPostProcessor) bp;
// 2.调用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition方法,
// 对指定bean的给定MergedBeanDefinition进行后置处理,@Autowire注解在这边对元数据进行预解析
//对postProcessMergedBeanDefinition进行依赖注解的搜集
bdp.postProcessMergedBeanDefinition(mbd, beanType, beanName);
}
}
}

​ 调用 MergedBeanDefinitionPostProcessor 的 postProcessMergedBeanDefinition 方法,对指定 bean 的给定MergedBeanDefinition进行后置处理,@Autowire 注解在这边对元数据进行预解析,之后会单独介绍。

addSingletonFactory

设置三级缓存,解决循环引用的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/**
* Add the given singleton factory for building the specified singleton
* if necessary.
* <p>To be called for eager registration of singletons, e.g. to be able to
* resolve circular references.
* 设置三级缓存
*/
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
// 1.如果beanName不存在于singletonObjects缓存中
//一级缓存不存在beanName
if (!this.singletonObjects.containsKey(beanName)) {
// 2.将beanName和singletonFactory注册到singletonFactories缓存(beanName -> 该beanName的单例工厂)
//设置beanName和匿名类的映射关系加入到三级缓存
this.singletonFactories.put(beanName, singletonFactory);
// 3.移除earlySingletonObjects缓存中的beanName(beanName -> beanName的早期单例对象)
this.earlySingletonObjects.remove(beanName);
// 4.将beanName注册到registeredSingletons缓存(已经注册的单例集合)
this.registeredSingletons.add(beanName);
}
}
}

​ 我们通过提前曝光的 ObjectFactory 获得 “不完整” 的 bean 实例,从而解决循环引用的问题,ObjectFactory 就是通过这边的 singletonObjects 缓存来进行曝光的。

getEarlyBeanReference

返回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
/**
* Obtain a reference for early access to the specified bean,
* typically for the purpose of resolving a circular reference.
* <p>
* 三级缓存对象工厂 ObjectFactory.getObject()调用到这个方法
* 返回bean的早期引用
*/
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
// 1.如果bean不为空 && mbd不是合成 && 存在InstantiationAwareBeanPostProcessors
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
//遍历所有的BeanPostProcessors
for (BeanPostProcessor bp : getBeanPostProcessors()) {
// 2.应用所有SmartInstantiationAwareBeanPostProcessor,调用getEarlyBeanReference方法
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
// 3.允许SmartInstantiationAwareBeanPostProcessor返回指定bean的早期引用
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
// 4.返回要作为bean引用公开的对象,如果没有SmartInstantiationAwareBeanPostProcessor修改,则返回的是入参的bean对象本身
return exposedObject;
}
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 中。

自动注入

Spring 会根据注入类型( byName / byType )的不同,调用不同的方法(autowireByName() / autowireByType())来注入属性值。

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);
}
}

实例化Bean的三种方式

​ 我们发现实例化Bean主要是三个方法

  • instantiateUsingFactoryMethod: 通工厂方式实例化Bean

  • autowireConstructor: 有参构造方法实例化Bean

  • **instantiateBean:**无参构造方法实例化Bean

先介绍一下实例化的大致流程

  1. 判断有无显式指定参数,如果有则优先使用,如xmlBeanFactory.getBean(“cat”, “美美”,3);
  2. 没有显式指定参数,则解析配置文件中的参数
  3. 优先尝试从缓存中获取,spring对参数的解析过程是比较复杂也耗时的,所以这里先尝 试从缓存中获取已经解析过的构造函数参数
  4. 缓存中不存在,则需要解析构造函数参数,以确定使用哪一个构造函数来进行实例化
  5. 使用指定的构造函数(如果有的话)。
  6. 如果指定的构造函数不存在,则根据方法访问级别,获取该bean所有的构造函数
  7. 对构造函数按照参数个数和参数类型进行排序,参数最多的构造函数会排在第一位
  8. 循环所有bean类中的构造函数,解析确定使用哪一个构造函数
  9. 获取ArgumentsHolder对象,直接理解为一个参数持有者即可
  10. 通过构造函数参数权重对比,得出最适合使用的构造函数
  11. 异常处理
  12. 缓存解析的构造函数
  13. 获取实例化策略并执行实例化
  14. 返回BeanWrapper包装类

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
26
27
28
29
30
/**
* Instantiate the given bean using its default constructor.
* 无参构造函数的实例化,大部分的实例是采用的无参构造函数的方式实例化
*/
protected BeanWrapper instantiateBean(final String beanName, final RootBeanDefinition mbd) {
try {
//实例对象的同期
Object beanInstance;
final BeanFactory parent = this;
//1. 实例化Bean
if (System.getSecurityManager() != null) {
beanInstance = AccessController.doPrivileged((PrivilegedAction<Object>) () ->
//1.1 有安全方式的实例化Bean
getInstantiationStrategy().instantiate(mbd, beanName, parent),
getAccessControlContext());
} else {
//1.2 正常方式实例化Bean
beanInstance = getInstantiationStrategy().instantiate(mbd, beanName, parent);
}
//2. 包装成BeanWrapper
BeanWrapper bw = new BeanWrapperImpl(beanInstance);
//3. 初始化BeanWrapper
initBeanWrapper(bw);
//4. 返回BeanWrapper
return bw;
} catch (Throwable ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Instantiation of bean failed", ex);
}
}

instantiate

默认构造方法实例化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
/**
* 默认构造方法实例化bean
*
* @param bd
* @param beanName
* @param owner
* @return
*/
@Override
public Object instantiate(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
// Don't override the class with CGLIB if no overrides.
//1. 如果没有methodOverride就不使用CGLIB
//bd中是否包含了MethodOverrides的列表,这里的Overrides并不是通常的意义上的多态,而是由spring提供的lookup-method,replaced-method标签生成的。
//如果没有MethodOverrides直接就可以实例化
if (!bd.hasMethodOverrides()) {
//声明需要初始化的构造方法
Constructor<?> constructorToUse;
//将这个db对象锁定,确保线程的安全
synchronized (bd.constructorArgumentLock) {
//1.1 从缓存中获取构造方法
constructorToUse = (Constructor<?>) bd.resolvedConstructorOrFactoryMethod;
//1.2 没有获取到情况下,就进行生成
if (constructorToUse == null) {
//1.3 获取bean的类型
final Class<?> clazz = bd.getBeanClass();
//如果是接口就无法实例化,抛出异常
if (clazz.isInterface()) {
throw new BeanInstantiationException(clazz, "Specified class is an interface");
}
try {
//1.4 获取默认的构造方法
//获取java的安全控制
if (System.getSecurityManager() != null) {
//1.4.1 获取到对应的权限进行初始化
constructorToUse = AccessController.doPrivileged(
(PrivilegedExceptionAction<Constructor<?>>) clazz::getDeclaredConstructor);
} else {
//1.4.2 获取构造方法
constructorToUse = clazz.getDeclaredConstructor();
}
//1.5 进行默认构造方法赋值
bd.resolvedConstructorOrFactoryMethod = constructorToUse;
} catch (Throwable ex) {
throw new BeanInstantiationException(clazz, "No default constructor found", ex);
}
}
}
//1.6 通过构造方法实例化bean 反射生成对象
return BeanUtils.instantiateClass(constructorToUse);
} else {
// Must generate CGLIB subclass.
//2. 如果有methodOverride就必须使用CGLIB进行实例化
return instantiateWithMethodInjection(bd, beanName, owner);
}
}

instantiateWithMethodInjection

如果有methodOverride就必须使用CGLIB进行实例化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
throw new UnsupportedOperationException("Method Injection not supported in SimpleInstantiationStrategy");
}

/**
* 实例化方法映射
*/
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner) {
//使用CGLib进行实例化
return instantiateWithMethodInjection(bd, beanName, owner, null);
}

//使用CGLib进行实例化
@Override
protected Object instantiateWithMethodInjection(RootBeanDefinition bd, @Nullable String beanName, BeanFactory owner,
@Nullable Constructor<?> ctor, Object... args) {

// Must generate CGLIB subclass...
//必须生成CGLib进行实例化
return new CglibSubclassCreator(bd, owner).instantiate(ctor, args);
}
instantiate

instantiateWithMethodInjection(bd, beanName, owner)通过一串委托之后,最终会调用到CglibSubclassingInstantiationStrategy类下的instantiate(@Nullable Constructor<?> ctor, Object… args)方法来完成代理对象的生成

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
/**
* Create a new instance of a dynamically generated subclass implementing the
* required lookups.
* 使用CGLIB进行Bean对象实例化
*/
public Object instantiate(@Nullable Constructor<?> ctor, Object... args) {
//1. cglib是通过创建被代理对象的子类,并重写方法完成代理过程。这里就是生成被代理对象的子类
Class<?> subclass = createEnhancedSubclass(this.beanDefinition);
Object instance;
if (ctor == null) {
//2. 如果没有构造方法,直接使用代理对象的构造方法实例化对象
instance = BeanUtils.instantiateClass(subclass);
} else {
try {
//3. 根据被代理对象的构造方法参数,找到代理对象的对应构造方法
Constructor<?> enhancedSubclassConstructor = subclass.getConstructor(ctor.getParameterTypes());
//4. 通过构造方法实例化代理对象
instance = enhancedSubclassConstructor.newInstance(args);
} catch (Exception ex) {
throw new BeanInstantiationException(this.beanDefinition.getBeanClass(),
"Failed to invoke constructor for CGLIB enhanced subclass [" + subclass.getName() + "]", ex);
}
}
// SPR-10785: set callbacks directly on the instance instead of in the
// enhanced class (via the Enhancer) in order to avoid memory leaks.
//5. 对实例化对象进行方法增强(详细使用查看cglib的使用)
Factory factory = (Factory) instance;
factory.setCallbacks(new Callback[]{NoOp.INSTANCE,
new LookupOverrideMethodInterceptor(this.beanDefinition, this.owner),
new ReplaceOverrideMethodInterceptor(this.beanDefinition, this.owner)});
return instance;
}

​ spring在做实例化策略的时候,首先判断了beanDefinition中是否有MethodOverrides,也就是用户有没有配置replace或者lookup的配置方法,如果没有配置就是直接使用反射的方式,简单粗暴的生成bean,但如果用户配置了这两方法,就不能这么简单的解决了,因为需要将这两个配置提供的功能切入进去,spring通过cglib的动态代理的方式将包含这两个特性对应的逻辑的拦截增强器设置进去,这样被代理对象的方法通过代理对象增强了。

评论