Skip to content
Projects
Groups
Snippets
Help
This project
Loading...
Sign in / Register
Toggle navigation
S
Spring_resource_analysis
Overview
Overview
Details
Activity
Cycle Analytics
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Issues
0
Issues
0
List
Board
Labels
Milestones
Merge Requests
0
Merge Requests
0
CI / CD
CI / CD
Pipelines
Jobs
Schedules
Charts
Wiki
Wiki
Snippets
Snippets
Members
Collapse sidebar
Close sidebar
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Open sidebar
WeifengSun
Spring_resource_analysis
Commits
307c9ae2
Commit
307c9ae2
authored
Aug 16, 2022
by
SunWei峰
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
BeanFactoryPostProcesser学习
parent
84f8a2e5
Hide whitespace changes
Inline
Side-by-side
Showing
11 changed files
with
246 additions
and
16 deletions
+246
-16
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
+44
-2
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
+2
-0
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java
+69
-1
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
+41
-0
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java
+7
-0
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
+30
-13
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableApplicationContext.java
+5
-0
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/ApplicationContextAwareProcessor.java
+1
-0
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/ClassPathXmlApplicationContext.java
+1
-0
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java
+42
-0
spring-framework-main/spring-web/src/main/java/org/springframework/web/context/support/XmlWebApplicationContext.java
+4
-0
No files found.
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractAutowireCapableBeanFactory.java
View file @
307c9ae2
...
@@ -56,6 +56,7 @@ import org.springframework.beans.factory.FactoryBean;
...
@@ -56,6 +56,7 @@ import org.springframework.beans.factory.FactoryBean;
import
org.springframework.beans.factory.InitializingBean
;
import
org.springframework.beans.factory.InitializingBean
;
import
org.springframework.beans.factory.InjectionPoint
;
import
org.springframework.beans.factory.InjectionPoint
;
import
org.springframework.beans.factory.UnsatisfiedDependencyException
;
import
org.springframework.beans.factory.UnsatisfiedDependencyException
;
import
org.springframework.beans.factory.annotation.Autowired
;
import
org.springframework.beans.factory.config.AutowireCapableBeanFactory
;
import
org.springframework.beans.factory.config.AutowireCapableBeanFactory
;
import
org.springframework.beans.factory.config.AutowiredPropertyMarker
;
import
org.springframework.beans.factory.config.AutowiredPropertyMarker
;
import
org.springframework.beans.factory.config.BeanDefinition
;
import
org.springframework.beans.factory.config.BeanDefinition
;
...
@@ -668,7 +669,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -668,7 +669,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Register bean as disposable.
// Register bean as disposable.
try
{
try
{
//
根据 Scopse 注册bean
//
注册 DisposableBean 销毁方法
registerDisposableBeanIfNecessary
(
beanName
,
bean
,
mbd
);
registerDisposableBeanIfNecessary
(
beanName
,
bean
,
mbd
);
}
}
catch
(
BeanDefinitionValidationException
ex
)
{
catch
(
BeanDefinitionValidationException
ex
)
{
...
@@ -1216,6 +1217,14 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1216,6 +1217,14 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
}
}
}
}
}
// RootBeanDefinition 中主要使用如下几个属性缓存 :
// 1. resolvedConstructorOrFactoryMethod : 用于缓存已解析的构造函数或工厂方法
// 2. constructorArgumentsResolved :这个字段有两层含义: 一,标记构造函数是否已经完成解析。
// 二,标志这个bean的加载是否 需要通过构造注入(autowireConstructor) 的方式加载。
// 因为只有在 autowireConstructor 方法中才会将其置为 true。
// 3. resolvedConstructorArguments : 缓存解析好的构造函数的入参
// 如果已经解析过则使用解析好的构造函数方法,不需要再次解析。
// 如果已经解析过则使用解析好的构造函数方法,不需要再次解析。
// 这里的是通过 mbd.resolvedConstructorOrFactoryMethod 属性来缓存解析过的构造函数。
// 这里的是通过 mbd.resolvedConstructorOrFactoryMethod 属性来缓存解析过的构造函数。
if
(
resolved
)
{
if
(
resolved
)
{
...
@@ -1407,6 +1416,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1407,6 +1416,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
*/
*/
@SuppressWarnings
(
"deprecation"
)
// for postProcessPropertyValues
@SuppressWarnings
(
"deprecation"
)
// for postProcessPropertyValues
protected
void
populateBean
(
String
beanName
,
RootBeanDefinition
mbd
,
@Nullable
BeanWrapper
bw
)
{
protected
void
populateBean
(
String
beanName
,
RootBeanDefinition
mbd
,
@Nullable
BeanWrapper
bw
)
{
// 标记了@Autowired
if
(
bw
==
null
)
{
if
(
bw
==
null
)
{
if
(
mbd
.
hasPropertyValues
())
{
if
(
mbd
.
hasPropertyValues
())
{
throw
new
BeanCreationException
(
throw
new
BeanCreationException
(
...
@@ -1421,8 +1431,11 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1421,8 +1431,11 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
// state of the bean before properties are set. This can be used, for example,
// state of the bean before properties are set. This can be used, for example,
// to support styles of field injection.
// to support styles of field injection.
// 给InstantiationAwareBeanPostProcessors最后一次机会在属性注入前修改Bean的属性值
// 具体通过调用postProcessAfterInstantiation方法,如果调用返回false,表示不必继续进行依赖注入,直接返回
if
(!
mbd
.
isSynthetic
()
&&
hasInstantiationAwareBeanPostProcessors
())
{
if
(!
mbd
.
isSynthetic
()
&&
hasInstantiationAwareBeanPostProcessors
())
{
for
(
InstantiationAwareBeanPostProcessor
bp
:
getBeanPostProcessorCache
().
instantiationAware
)
{
for
(
InstantiationAwareBeanPostProcessor
bp
:
getBeanPostProcessorCache
().
instantiationAware
)
{
// 返回值为是否继续填充bean
if
(!
bp
.
postProcessAfterInstantiation
(
bw
.
getWrappedInstance
(),
beanName
))
{
if
(!
bp
.
postProcessAfterInstantiation
(
bw
.
getWrappedInstance
(),
beanName
))
{
return
;
return
;
}
}
...
@@ -1432,6 +1445,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1432,6 +1445,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
PropertyValues
pvs
=
(
mbd
.
hasPropertyValues
()
?
mbd
.
getPropertyValues
()
:
null
);
PropertyValues
pvs
=
(
mbd
.
hasPropertyValues
()
?
mbd
.
getPropertyValues
()
:
null
);
int
resolvedAutowireMode
=
mbd
.
getResolvedAutowireMode
();
int
resolvedAutowireMode
=
mbd
.
getResolvedAutowireMode
();
// 2. 自动装配 :根据名称或类型自动注入
if
(
resolvedAutowireMode
==
AUTOWIRE_BY_NAME
||
resolvedAutowireMode
==
AUTOWIRE_BY_TYPE
)
{
if
(
resolvedAutowireMode
==
AUTOWIRE_BY_NAME
||
resolvedAutowireMode
==
AUTOWIRE_BY_TYPE
)
{
MutablePropertyValues
newPvs
=
new
MutablePropertyValues
(
pvs
);
MutablePropertyValues
newPvs
=
new
MutablePropertyValues
(
pvs
);
// Add property values based on autowire by name if applicable.
// Add property values based on autowire by name if applicable.
...
@@ -1445,13 +1459,18 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1445,13 +1459,18 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
pvs
=
newPvs
;
pvs
=
newPvs
;
}
}
// 后处理器已经初始化
boolean
hasInstAwareBpps
=
hasInstantiationAwareBeanPostProcessors
();
boolean
hasInstAwareBpps
=
hasInstantiationAwareBeanPostProcessors
();
// 需要依赖检查
boolean
needsDepCheck
=
(
mbd
.
getDependencyCheck
()
!=
AbstractBeanDefinition
.
DEPENDENCY_CHECK_NONE
);
boolean
needsDepCheck
=
(
mbd
.
getDependencyCheck
()
!=
AbstractBeanDefinition
.
DEPENDENCY_CHECK_NONE
);
if
(
hasInstAwareBpps
)
{
if
(
hasInstAwareBpps
)
{
if
(
pvs
==
null
)
{
if
(
pvs
==
null
)
{
pvs
=
mbd
.
getPropertyValues
();
pvs
=
mbd
.
getPropertyValues
();
}
}
// 3. 成员变量的注入
// 调用了InstantiationAwareBeanPostProcessor.postProcessProperties 方法
// 和 postProcessPropertyValues 方法 来进行设值后处理
for
(
InstantiationAwareBeanPostProcessor
bp
:
getBeanPostProcessorCache
().
instantiationAware
)
{
for
(
InstantiationAwareBeanPostProcessor
bp
:
getBeanPostProcessorCache
().
instantiationAware
)
{
PropertyValues
pvsToUse
=
bp
.
postProcessProperties
(
pvs
,
bw
.
getWrappedInstance
(),
beanName
);
PropertyValues
pvsToUse
=
bp
.
postProcessProperties
(
pvs
,
bw
.
getWrappedInstance
(),
beanName
);
if
(
pvsToUse
==
null
)
{
if
(
pvsToUse
==
null
)
{
...
@@ -1462,9 +1481,11 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1462,9 +1481,11 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
}
}
if
(
needsDepCheck
)
{
if
(
needsDepCheck
)
{
PropertyDescriptor
[]
filteredPds
=
filterPropertyDescriptorsForDependencyCheck
(
bw
,
mbd
.
allowCaching
);
PropertyDescriptor
[]
filteredPds
=
filterPropertyDescriptorsForDependencyCheck
(
bw
,
mbd
.
allowCaching
);
// 依赖检查,对应 depends-on 属性,3.0 已弃用
checkDependencies
(
beanName
,
mbd
,
filteredPds
,
pvs
);
checkDependencies
(
beanName
,
mbd
,
filteredPds
,
pvs
);
}
}
// 4. 将属性应用到bean中
if
(
pvs
!=
null
)
{
if
(
pvs
!=
null
)
{
applyPropertyValues
(
beanName
,
mbd
,
bw
,
pvs
);
applyPropertyValues
(
beanName
,
mbd
,
bw
,
pvs
);
}
}
...
@@ -1482,11 +1503,16 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1482,11 +1503,16 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
protected
void
autowireByName
(
protected
void
autowireByName
(
String
beanName
,
AbstractBeanDefinition
mbd
,
BeanWrapper
bw
,
MutablePropertyValues
pvs
)
{
String
beanName
,
AbstractBeanDefinition
mbd
,
BeanWrapper
bw
,
MutablePropertyValues
pvs
)
{
// 寻找bw中需要依赖注入的属性name
String
[]
propertyNames
=
unsatisfiedNonSimpleProperties
(
mbd
,
bw
);
String
[]
propertyNames
=
unsatisfiedNonSimpleProperties
(
mbd
,
bw
);
for
(
String
propertyName
:
propertyNames
)
{
for
(
String
propertyName
:
propertyNames
)
{
// 检查缓存 bean 中是否有当前bean
if
(
containsBean
(
propertyName
))
{
if
(
containsBean
(
propertyName
))
{
// 递归初始化bean,会调用doGetBean 来 获取bean
Object
bean
=
getBean
(
propertyName
);
Object
bean
=
getBean
(
propertyName
);
pvs
.
add
(
propertyName
,
bean
);
pvs
.
add
(
propertyName
,
bean
);
// 注册依赖,将依赖关系保存到 Map<String, Set<String>> dependentBeanMapdependentBeanMap 中,
// key是 bean,value是 转化后的 propertyName
registerDependentBean
(
propertyName
,
beanName
);
registerDependentBean
(
propertyName
,
beanName
);
if
(
logger
.
isTraceEnabled
())
{
if
(
logger
.
isTraceEnabled
())
{
logger
.
trace
(
"Added autowiring by name from bean name '"
+
beanName
+
logger
.
trace
(
"Added autowiring by name from bean name '"
+
beanName
+
...
@@ -1516,28 +1542,40 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1516,28 +1542,40 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
protected
void
autowireByType
(
protected
void
autowireByType
(
String
beanName
,
AbstractBeanDefinition
mbd
,
BeanWrapper
bw
,
MutablePropertyValues
pvs
)
{
String
beanName
,
AbstractBeanDefinition
mbd
,
BeanWrapper
bw
,
MutablePropertyValues
pvs
)
{
// 获取自定义的类型转换器
TypeConverter
converter
=
getCustomTypeConverter
();
TypeConverter
converter
=
getCustomTypeConverter
();
if
(
converter
==
null
)
{
if
(
converter
==
null
)
{
converter
=
bw
;
converter
=
bw
;
}
}
// 集合属性
Set
<
String
>
autowiredBeanNames
=
new
LinkedHashSet
<>(
4
);
Set
<
String
>
autowiredBeanNames
=
new
LinkedHashSet
<>(
4
);
// 寻找 bw 中需要依赖注入的属性name
String
[]
propertyNames
=
unsatisfiedNonSimpleProperties
(
mbd
,
bw
);
String
[]
propertyNames
=
unsatisfiedNonSimpleProperties
(
mbd
,
bw
);
for
(
String
propertyName
:
propertyNames
)
{
for
(
String
propertyName
:
propertyNames
)
{
try
{
try
{
// 获取属性描述符
PropertyDescriptor
pd
=
bw
.
getPropertyDescriptor
(
propertyName
);
PropertyDescriptor
pd
=
bw
.
getPropertyDescriptor
(
propertyName
);
// Don't try autowiring by type for type Object: never makes sense,
// Don't try autowiring by type for type Object: never makes sense,
// even if it technically is a unsatisfied, non-simple property.
// even if it technically is a unsatisfied, non-simple property.
// 不要尝试按类型为Object类型自动装配:即使从技术上讲是不满意的,非简单的属性,也从没有意义。
if
(
Object
.
class
!=
pd
.
getPropertyType
())
{
if
(
Object
.
class
!=
pd
.
getPropertyType
())
{
// 获取指定属性的 set 方法
MethodParameter
methodParam
=
BeanUtils
.
getWriteMethodParameter
(
pd
);
MethodParameter
methodParam
=
BeanUtils
.
getWriteMethodParameter
(
pd
);
// Do not allow eager init for type matching in case of a prioritized post-processor.
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean
eager
=
!(
bw
.
getWrappedInstance
()
instanceof
PriorityOrdered
);
boolean
eager
=
!(
bw
.
getWrappedInstance
()
instanceof
PriorityOrdered
);
DependencyDescriptor
desc
=
new
AutowireByTypeDependencyDescriptor
(
methodParam
,
eager
);
DependencyDescriptor
desc
=
new
AutowireByTypeDependencyDescriptor
(
methodParam
,
eager
);
Object
autowiredArgument
=
resolveDependency
(
desc
,
beanName
,
autowiredBeanNames
,
converter
);
// 解析指定beanName 的属性所匹配的值,并把解析到的属性名存储在 autowiredBeanNames 中
// 当属性存在多个封装bean时,如 @Autowired List<Bean> beans,会找到所有的匹配Bean 类型的bean并将其注入。
// 这里的返回值是真正的需要注入的属性, autowiredBeanNames 是需要注入的属性(可能是集合)的names
Object
autowiredArgument
=
resolveDependency
(
desc
,
beanName
,
autowiredBeanNames
,
converter
);
if
(
autowiredArgument
!=
null
)
{
if
(
autowiredArgument
!=
null
)
{
// 添加到待注入的bean列表中
pvs
.
add
(
propertyName
,
autowiredArgument
);
pvs
.
add
(
propertyName
,
autowiredArgument
);
}
}
// 注册依赖
for
(
String
autowiredBeanName
:
autowiredBeanNames
)
{
for
(
String
autowiredBeanName
:
autowiredBeanNames
)
{
// 注册依赖关系。操作 dependentBeanMap 和 dependenciesForBeanMap 集合
registerDependentBean
(
autowiredBeanName
,
beanName
);
registerDependentBean
(
autowiredBeanName
,
beanName
);
if
(
logger
.
isTraceEnabled
())
{
if
(
logger
.
isTraceEnabled
())
{
logger
.
trace
(
"Autowiring by type from bean name '"
+
beanName
+
"' via property '"
+
logger
.
trace
(
"Autowiring by type from bean name '"
+
beanName
+
"' via property '"
+
...
@@ -1794,14 +1832,17 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1794,14 +1832,17 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
* @see #applyBeanPostProcessorsAfterInitialization
* @see #applyBeanPostProcessorsAfterInitialization
*/
*/
protected
Object
initializeBean
(
String
beanName
,
Object
bean
,
@Nullable
RootBeanDefinition
mbd
)
{
protected
Object
initializeBean
(
String
beanName
,
Object
bean
,
@Nullable
RootBeanDefinition
mbd
)
{
// 激活 Aware 方法
invokeAwareMethods
(
beanName
,
bean
);
invokeAwareMethods
(
beanName
,
bean
);
Object
wrappedBean
=
bean
;
Object
wrappedBean
=
bean
;
if
(
mbd
==
null
||
!
mbd
.
isSynthetic
())
{
if
(
mbd
==
null
||
!
mbd
.
isSynthetic
())
{
// 调用了bean前置处理器的方法
wrappedBean
=
applyBeanPostProcessorsBeforeInitialization
(
wrappedBean
,
beanName
);
wrappedBean
=
applyBeanPostProcessorsBeforeInitialization
(
wrappedBean
,
beanName
);
}
}
try
{
try
{
// 激活自定义的init的方法。
invokeInitMethods
(
beanName
,
wrappedBean
,
mbd
);
invokeInitMethods
(
beanName
,
wrappedBean
,
mbd
);
}
}
catch
(
Throwable
ex
)
{
catch
(
Throwable
ex
)
{
...
@@ -1810,6 +1851,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
...
@@ -1810,6 +1851,7 @@ public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFac
beanName
,
"Invocation of init method failed"
,
ex
);
beanName
,
"Invocation of init method failed"
,
ex
);
}
}
if
(
mbd
==
null
||
!
mbd
.
isSynthetic
())
{
if
(
mbd
==
null
||
!
mbd
.
isSynthetic
())
{
// 调用了bean后置处理器的方法
wrappedBean
=
applyBeanPostProcessorsAfterInitialization
(
wrappedBean
,
beanName
);
wrappedBean
=
applyBeanPostProcessorsAfterInitialization
(
wrappedBean
,
beanName
);
}
}
...
...
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/AbstractBeanFactory.java
View file @
307c9ae2
...
@@ -1912,6 +1912,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
...
@@ -1912,6 +1912,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
*/
*/
protected
void
registerDisposableBeanIfNecessary
(
String
beanName
,
Object
bean
,
RootBeanDefinition
mbd
)
{
protected
void
registerDisposableBeanIfNecessary
(
String
beanName
,
Object
bean
,
RootBeanDefinition
mbd
)
{
if
(!
mbd
.
isPrototype
()
&&
requiresDestruction
(
bean
,
mbd
))
{
if
(!
mbd
.
isPrototype
()
&&
requiresDestruction
(
bean
,
mbd
))
{
// 单例模式下才注册需要销毁的bean
if
(
mbd
.
isSingleton
())
{
if
(
mbd
.
isSingleton
())
{
// Register a DisposableBean implementation that performs all destruction
// Register a DisposableBean implementation that performs all destruction
// work for the given bean: DestructionAwareBeanPostProcessors,
// work for the given bean: DestructionAwareBeanPostProcessors,
...
@@ -1919,6 +1920,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
...
@@ -1919,6 +1920,7 @@ public abstract class AbstractBeanFactory extends FactoryBeanRegistrySupport imp
registerDisposableBean
(
beanName
,
new
DisposableBeanAdapter
(
registerDisposableBean
(
beanName
,
new
DisposableBeanAdapter
(
bean
,
beanName
,
mbd
,
getBeanPostProcessorCache
().
destructionAware
));
bean
,
beanName
,
mbd
,
getBeanPostProcessorCache
().
destructionAware
));
}
}
// 自定义的 scope
else
{
else
{
// A bean with a custom scope...
// A bean with a custom scope...
Scope
scope
=
this
.
scopes
.
get
(
mbd
.
getScope
());
Scope
scope
=
this
.
scopes
.
get
(
mbd
.
getScope
());
...
...
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/ConstructorResolver.java
View file @
307c9ae2
...
@@ -124,40 +124,63 @@ class ConstructorResolver {
...
@@ -124,40 +124,63 @@ class ConstructorResolver {
*/
*/
public
BeanWrapper
autowireConstructor
(
String
beanName
,
RootBeanDefinition
mbd
,
public
BeanWrapper
autowireConstructor
(
String
beanName
,
RootBeanDefinition
mbd
,
@Nullable
Constructor
<?>[]
chosenCtors
,
@Nullable
Object
[]
explicitArgs
)
{
@Nullable
Constructor
<?>[]
chosenCtors
,
@Nullable
Object
[]
explicitArgs
)
{
// 根据传入的参数列表,来匹配到合适的构造函数进行 bean 的创建。
// chosenCtors : 候选构造函数列表, 没有则为null
// explicitArgs : 通过getBean方法以编程方式传递的参数值,
BeanWrapperImpl
bw
=
new
BeanWrapperImpl
();
BeanWrapperImpl
bw
=
new
BeanWrapperImpl
();
this
.
beanFactory
.
initBeanWrapper
(
bw
);
this
.
beanFactory
.
initBeanWrapper
(
bw
);
// 候选的构造函数列表
Constructor
<?>
constructorToUse
=
null
;
Constructor
<?>
constructorToUse
=
null
;
ArgumentsHolder
argsHolderToUse
=
null
;
ArgumentsHolder
argsHolderToUse
=
null
;
// 构造函数最后确定使用的参数
Object
[]
argsToUse
=
null
;
Object
[]
argsToUse
=
null
;
// 1. 解析构造函数参数
// explicitArgs 参数是通过 getBean 方法传入
// 如果 getBean在调用时传入了参数,那么直接使用即可。getBean 调用的传参,
// 不用从缓存中获取构造函数,需要进行筛选匹配(个人理解,getBean 方法的入参可能并不相同,缓存的构造函数可能并不适用)
if
(
explicitArgs
!=
null
)
{
if
(
explicitArgs
!=
null
)
{
argsToUse
=
explicitArgs
;
argsToUse
=
explicitArgs
;
}
}
// 否则 尝试从 BeanDefinition 中加载缓存的bean构造时需要的参数
else
{
else
{
Object
[]
argsToResolve
=
null
;
Object
[]
argsToResolve
=
null
;
synchronized
(
mbd
.
constructorArgumentLock
)
{
synchronized
(
mbd
.
constructorArgumentLock
)
{
// 从缓存中获取要使用的构造函数。没有缓存则为null
constructorToUse
=
(
Constructor
<?>)
mbd
.
resolvedConstructorOrFactoryMethod
;
constructorToUse
=
(
Constructor
<?>)
mbd
.
resolvedConstructorOrFactoryMethod
;
// 如果构造函数不为空 && 构造函数参数已经解析
if
(
constructorToUse
!=
null
&&
mbd
.
constructorArgumentsResolved
)
{
if
(
constructorToUse
!=
null
&&
mbd
.
constructorArgumentsResolved
)
{
// Found a cached constructor...
// Found a cached constructor...
// 从缓存中获取。这里如果不能获取到完全解析好的参数,则获取尚未解析的参数,进行解析后再赋值给 argsToUse
// resolvedConstructorArguments 是完全解析好的构造函数参数
argsToUse
=
mbd
.
resolvedConstructorArguments
;
argsToUse
=
mbd
.
resolvedConstructorArguments
;
if
(
argsToUse
==
null
)
{
if
(
argsToUse
==
null
)
{
// 配置构造函数参数
// preparedConstructorArguments 是尚未完全解析的构造函数参数
argsToResolve
=
mbd
.
preparedConstructorArguments
;
argsToResolve
=
mbd
.
preparedConstructorArguments
;
}
}
}
}
}
}
// 如果缓存中存在尚未完全解析的参数列表,则进行进一步的解析
if
(
argsToResolve
!=
null
)
{
if
(
argsToResolve
!=
null
)
{
// 解析参数类型,如给定的参数列表为(int,int),这时就会将配置中的("1", "1") 转化为 (1,1)
// 缓存中的值可能是最终值,也可能是原始值,因为不一定需要类型转换
argsToUse
=
resolvePreparedArguments
(
beanName
,
mbd
,
bw
,
constructorToUse
,
argsToResolve
);
argsToUse
=
resolvePreparedArguments
(
beanName
,
mbd
,
bw
,
constructorToUse
,
argsToResolve
);
}
}
}
}
// 如果构造函数 和 构造函数入参 都不为空,则可以直接生成bean。否则的话,需要通过一定的规则进行筛选
if
(
constructorToUse
==
null
||
argsToUse
==
null
)
{
if
(
constructorToUse
==
null
||
argsToUse
==
null
)
{
// Take specified constructors, if any.
// Take specified constructors, if any.
// chosenCtors 是候选的构造函数,如果存在候选的构造函数,则跳过这里,否则通过反射获取bean的构造函数集合
// 2. 获取候选的构造参数列表
Constructor
<?>[]
candidates
=
chosenCtors
;
Constructor
<?>[]
candidates
=
chosenCtors
;
if
(
candidates
==
null
)
{
if
(
candidates
==
null
)
{
Class
<?>
beanClass
=
mbd
.
getBeanClass
();
Class
<?>
beanClass
=
mbd
.
getBeanClass
();
try
{
try
{
// 反射获取bean的构造函数集合
candidates
=
(
mbd
.
isNonPublicAccessAllowed
()
?
candidates
=
(
mbd
.
isNonPublicAccessAllowed
()
?
beanClass
.
getDeclaredConstructors
()
:
beanClass
.
getConstructors
());
beanClass
.
getDeclaredConstructors
()
:
beanClass
.
getConstructors
());
}
}
...
@@ -168,62 +191,96 @@ class ConstructorResolver {
...
@@ -168,62 +191,96 @@ class ConstructorResolver {
}
}
}
}
// 如果构造函数只有一个 && getBean 没有传参 && 构造参数无参
// 满足上述三个条件,则无需继续筛选构造函数,直接使用唯一一个构造函数创建 BeanWrapper 并返回即可。
if
(
candidates
.
length
==
1
&&
explicitArgs
==
null
&&
!
mbd
.
hasConstructorArgumentValues
())
{
if
(
candidates
.
length
==
1
&&
explicitArgs
==
null
&&
!
mbd
.
hasConstructorArgumentValues
())
{
Constructor
<?>
uniqueCandidate
=
candidates
[
0
];
Constructor
<?>
uniqueCandidate
=
candidates
[
0
];
// 确定该构造函数为无参
if
(
uniqueCandidate
.
getParameterCount
()
==
0
)
{
if
(
uniqueCandidate
.
getParameterCount
()
==
0
)
{
synchronized
(
mbd
.
constructorArgumentLock
)
{
synchronized
(
mbd
.
constructorArgumentLock
)
{
// 将解析结束的信息缓存到 mdb中
// 缓存解析出来的唯一 构造函数
mbd
.
resolvedConstructorOrFactoryMethod
=
uniqueCandidate
;
mbd
.
resolvedConstructorOrFactoryMethod
=
uniqueCandidate
;
// 标记构造函数已经完全解析
mbd
.
constructorArgumentsResolved
=
true
;
mbd
.
constructorArgumentsResolved
=
true
;
// 缓存解析好的构造函数参数。这里是空数组 (Object[] EMPTY_ARGS = new Object[0];)
mbd
.
resolvedConstructorArguments
=
EMPTY_ARGS
;
mbd
.
resolvedConstructorArguments
=
EMPTY_ARGS
;
}
}
// 调用 instantiate 方法创建对象实例并保存到 bw中
bw
.
setBeanInstance
(
instantiate
(
beanName
,
mbd
,
uniqueCandidate
,
EMPTY_ARGS
));
bw
.
setBeanInstance
(
instantiate
(
beanName
,
mbd
,
uniqueCandidate
,
EMPTY_ARGS
));
return
bw
;
return
bw
;
}
}
}
}
// Need to resolve the constructor.
// Need to resolve the constructor.
// 待选构造函数列表不为null || 需要构造注入,则需要解析。
// mbd.getResolvedAutowireMode() 是针对 xml 注入的
boolean
autowiring
=
(
chosenCtors
!=
null
||
boolean
autowiring
=
(
chosenCtors
!=
null
||
mbd
.
getResolvedAutowireMode
()
==
AutowireCapableBeanFactory
.
AUTOWIRE_CONSTRUCTOR
);
mbd
.
getResolvedAutowireMode
()
==
AutowireCapableBeanFactory
.
AUTOWIRE_CONSTRUCTOR
);
ConstructorArgumentValues
resolvedValues
=
null
;
ConstructorArgumentValues
resolvedValues
=
null
;
// 3. 解析出来的参数的个数
int
minNrOfArgs
;
int
minNrOfArgs
;
// 如果explicitArgs 不为空,直接使用它作为参数,毕竟是传入的参数,没必要再从进一步解析。
if
(
explicitArgs
!=
null
)
{
if
(
explicitArgs
!=
null
)
{
minNrOfArgs
=
explicitArgs
.
length
;
minNrOfArgs
=
explicitArgs
.
length
;
}
}
else
{
else
{
// 获取xml配置文件中的配置的构造函数参数
ConstructorArgumentValues
cargs
=
mbd
.
getConstructorArgumentValues
();
ConstructorArgumentValues
cargs
=
mbd
.
getConstructorArgumentValues
();
// 用于承载解析后的构造函数参数的值
resolvedValues
=
new
ConstructorArgumentValues
();
resolvedValues
=
new
ConstructorArgumentValues
();
// 确定解析到的构造函数参数个数并进行类型转换匹配。在下面有详细解读
minNrOfArgs
=
resolveConstructorArguments
(
beanName
,
mbd
,
bw
,
cargs
,
resolvedValues
);
minNrOfArgs
=
resolveConstructorArguments
(
beanName
,
mbd
,
bw
,
cargs
,
resolvedValues
);
}
}
// 4. 寻找最匹配的构造函数
// 对构造函数列表进行排序: public 构造函数优先参数数量降序,非public构造函数参数数量降序
AutowireUtils
.
sortConstructors
(
candidates
);
AutowireUtils
.
sortConstructors
(
candidates
);
int
minTypeDiffWeight
=
Integer
.
MAX_VALUE
;
int
minTypeDiffWeight
=
Integer
.
MAX_VALUE
;
Set
<
Constructor
<?>>
ambiguousConstructors
=
null
;
Set
<
Constructor
<?>>
ambiguousConstructors
=
null
;
Deque
<
UnsatisfiedDependencyException
>
causes
=
null
;
Deque
<
UnsatisfiedDependencyException
>
causes
=
null
;
// 遍历构造函数,寻找合适的构造函数
for
(
Constructor
<?>
candidate
:
candidates
)
{
for
(
Constructor
<?>
candidate
:
candidates
)
{
// 获取当前构造函数参数个数
int
parameterCount
=
candidate
.
getParameterCount
();
int
parameterCount
=
candidate
.
getParameterCount
();
// 如果已经找到选用的构造函数 (argstoUse != null) 或者 需要的构造函数的参数个数 大于 当前构造函数参数个数 则终止
// constructorToUse != null 说明找到了构造函数
// argsToUse != null 说明参数已经赋值
// argsToUse.length > parameterCount
// 即已经找到适配的构造函数(可能不是最终的,但参数数量一定相同),
// 预选构造函数的参数数量 大于 当前构造函数的数量,可以直接break,因为按照参数数量降序排序,这里如果小于就没有必要继续比较下去
if
(
constructorToUse
!=
null
&&
argsToUse
!=
null
&&
argsToUse
.
length
>
parameterCount
)
{
if
(
constructorToUse
!=
null
&&
argsToUse
!=
null
&&
argsToUse
.
length
>
parameterCount
)
{
// Already found greedy constructor that can be satisfied ->
// Already found greedy constructor that can be satisfied ->
// do not look any further, there are only less greedy constructors left.
// do not look any further, there are only less greedy constructors left.
break
;
break
;
}
}
if
(
parameterCount
<
minNrOfArgs
)
{
if
(
parameterCount
<
minNrOfArgs
)
{
// 参数数量不相等,跳过
continue
;
continue
;
}
}
// 到这里说明尚未找到构造函数,且目前的构造函数和需要的构造函数参数个数相同,下面要对类型进行比较。
ArgumentsHolder
argsHolder
;
ArgumentsHolder
argsHolder
;
Class
<?>[]
paramTypes
=
candidate
.
getParameterTypes
();
Class
<?>[]
paramTypes
=
candidate
.
getParameterTypes
();
// 如果构造函数存在参数,resolvedValues 是上面解析后的构造函数,有参则根据 值 构造对应参数类型的参数
if
(
resolvedValues
!=
null
)
{
if
(
resolvedValues
!=
null
)
{
try
{
try
{
// 获取参数名称
// 从 @ConstructorProperties 注解上获取参数名称
String
[]
paramNames
=
ConstructorPropertiesChecker
.
evaluate
(
candidate
,
parameterCount
);
String
[]
paramNames
=
ConstructorPropertiesChecker
.
evaluate
(
candidate
,
parameterCount
);
// 为null则说明没有使用注解
if
(
paramNames
==
null
)
{
if
(
paramNames
==
null
)
{
// 获取参数名称探索器
ParameterNameDiscoverer
pnd
=
this
.
beanFactory
.
getParameterNameDiscoverer
();
ParameterNameDiscoverer
pnd
=
this
.
beanFactory
.
getParameterNameDiscoverer
();
if
(
pnd
!=
null
)
{
if
(
pnd
!=
null
)
{
// 获取指定的构造函数的参数名称
paramNames
=
pnd
.
getParameterNames
(
candidate
);
paramNames
=
pnd
.
getParameterNames
(
candidate
);
}
}
}
}
// 根据类型和数据类型创建 参数持有者
// 这里会调用 DefaultListableBeanFactory#resolveDependency 方法来解析依赖关系
argsHolder
=
createArgumentArray
(
beanName
,
mbd
,
resolvedValues
,
bw
,
paramTypes
,
paramNames
,
argsHolder
=
createArgumentArray
(
beanName
,
mbd
,
resolvedValues
,
bw
,
paramTypes
,
paramNames
,
getUserDeclaredConstructor
(
candidate
),
autowiring
,
candidates
.
length
==
1
);
getUserDeclaredConstructor
(
candidate
),
autowiring
,
candidates
.
length
==
1
);
}
}
...
@@ -240,17 +297,23 @@ class ConstructorResolver {
...
@@ -240,17 +297,23 @@ class ConstructorResolver {
}
}
}
}
else
{
else
{
// 如果构造函数为默认构造函数,没有参数,如果参数不完全一致则跳过
// Explicit arguments given -> arguments length must match exactly.
// Explicit arguments given -> arguments length must match exactly.
if
(
parameterCount
!=
explicitArgs
.
length
)
{
if
(
parameterCount
!=
explicitArgs
.
length
)
{
continue
;
continue
;
}
}
// 构造函数没有参数的情况
argsHolder
=
new
ArgumentsHolder
(
explicitArgs
);
argsHolder
=
new
ArgumentsHolder
(
explicitArgs
);
}
}
// 探测是否有不确定性的构造函数存在,例如不同构造函数的参数为父子关系
int
typeDiffWeight
=
(
mbd
.
isLenientConstructorResolution
()
?
int
typeDiffWeight
=
(
mbd
.
isLenientConstructorResolution
()
?
argsHolder
.
getTypeDifferenceWeight
(
paramTypes
)
:
argsHolder
.
getAssignabilityWeight
(
paramTypes
));
argsHolder
.
getTypeDifferenceWeight
(
paramTypes
)
:
argsHolder
.
getAssignabilityWeight
(
paramTypes
));
// Choose this constructor if it represents the closest match.
// Choose this constructor if it represents the closest match.
// 如果他是当前最接近匹配则选择作为构造函数,因为可能有多个构造函数都同时满足,比如构造函数参数类型全是 Object,
// 选择最合适的(typeDiffWeight 最小的)作为最终构造函数
if
(
typeDiffWeight
<
minTypeDiffWeight
)
{
if
(
typeDiffWeight
<
minTypeDiffWeight
)
{
// 找到最匹配的构造函数赋值保存
constructorToUse
=
candidate
;
constructorToUse
=
candidate
;
argsHolderToUse
=
argsHolder
;
argsHolderToUse
=
argsHolder
;
argsToUse
=
argsHolder
.
arguments
;
argsToUse
=
argsHolder
.
arguments
;
...
@@ -258,6 +321,7 @@ class ConstructorResolver {
...
@@ -258,6 +321,7 @@ class ConstructorResolver {
ambiguousConstructors
=
null
;
ambiguousConstructors
=
null
;
}
}
else
if
(
constructorToUse
!=
null
&&
typeDiffWeight
==
minTypeDiffWeight
)
{
else
if
(
constructorToUse
!=
null
&&
typeDiffWeight
==
minTypeDiffWeight
)
{
// 如果 已经找到候选构造函数,且当前这个构造函数也有相同的类似度则保存到 ambiguousConstructors 中。后面用于抛出异常
if
(
ambiguousConstructors
==
null
)
{
if
(
ambiguousConstructors
==
null
)
{
ambiguousConstructors
=
new
LinkedHashSet
<>();
ambiguousConstructors
=
new
LinkedHashSet
<>();
ambiguousConstructors
.
add
(
constructorToUse
);
ambiguousConstructors
.
add
(
constructorToUse
);
...
@@ -266,6 +330,7 @@ class ConstructorResolver {
...
@@ -266,6 +330,7 @@ class ConstructorResolver {
}
}
}
}
// 如果 constructorToUse 构造函数为 null,则查找构造函数失败,抛出异常
if
(
constructorToUse
==
null
)
{
if
(
constructorToUse
==
null
)
{
if
(
causes
!=
null
)
{
if
(
causes
!=
null
)
{
UnsatisfiedDependencyException
ex
=
causes
.
removeLast
();
UnsatisfiedDependencyException
ex
=
causes
.
removeLast
();
...
@@ -278,6 +343,7 @@ class ConstructorResolver {
...
@@ -278,6 +343,7 @@ class ConstructorResolver {
"Could not resolve matching constructor on bean class ["
+
mbd
.
getBeanClassName
()
+
"] "
+
"Could not resolve matching constructor on bean class ["
+
mbd
.
getBeanClassName
()
+
"] "
+
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)"
);
"(hint: specify index/type/name arguments for simple parameters to avoid type ambiguities)"
);
}
}
// 如果ambiguousConstructors 不为空说明有多个构造函数可适配,并且 如果不允许多个存在,则抛出异常
else
if
(
ambiguousConstructors
!=
null
&&
!
mbd
.
isLenientConstructorResolution
())
{
else
if
(
ambiguousConstructors
!=
null
&&
!
mbd
.
isLenientConstructorResolution
())
{
throw
new
BeanCreationException
(
mbd
.
getResourceDescription
(),
beanName
,
throw
new
BeanCreationException
(
mbd
.
getResourceDescription
(),
beanName
,
"Ambiguous constructor matches found on bean class ["
+
mbd
.
getBeanClassName
()
+
"] "
+
"Ambiguous constructor matches found on bean class ["
+
mbd
.
getBeanClassName
()
+
"] "
+
...
@@ -285,11 +351,13 @@ class ConstructorResolver {
...
@@ -285,11 +351,13 @@ class ConstructorResolver {
ambiguousConstructors
);
ambiguousConstructors
);
}
}
// 将解析的构造函数加入缓存
if
(
explicitArgs
==
null
&&
argsHolderToUse
!=
null
)
{
if
(
explicitArgs
==
null
&&
argsHolderToUse
!=
null
)
{
argsHolderToUse
.
storeCache
(
mbd
,
constructorToUse
);
argsHolderToUse
.
storeCache
(
mbd
,
constructorToUse
);
}
}
}
}
// 将构建的实例加入BeanWrapper 中
Assert
.
state
(
argsToUse
!=
null
,
"Unresolved constructor arguments"
);
Assert
.
state
(
argsToUse
!=
null
,
"Unresolved constructor arguments"
);
bw
.
setBeanInstance
(
instantiate
(
beanName
,
mbd
,
constructorToUse
,
argsToUse
));
bw
.
setBeanInstance
(
instantiate
(
beanName
,
mbd
,
constructorToUse
,
argsToUse
));
return
bw
;
return
bw
;
...
...
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/DefaultListableBeanFactory.java
View file @
307c9ae2
...
@@ -1301,8 +1301,10 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1301,8 +1301,10 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
@Nullable
@Nullable
public
Object
resolveDependency
(
DependencyDescriptor
descriptor
,
@Nullable
String
requestingBeanName
,
public
Object
resolveDependency
(
DependencyDescriptor
descriptor
,
@Nullable
String
requestingBeanName
,
@Nullable
Set
<
String
>
autowiredBeanNames
,
@Nullable
TypeConverter
typeConverter
)
throws
BeansException
{
@Nullable
Set
<
String
>
autowiredBeanNames
,
@Nullable
TypeConverter
typeConverter
)
throws
BeansException
{
// 寻找匹配的类型
descriptor
.
initParameterNameDiscovery
(
getParameterNameDiscoverer
());
descriptor
.
initParameterNameDiscovery
(
getParameterNameDiscoverer
());
// 针对不同类型的不同处理
if
(
Optional
.
class
==
descriptor
.
getDependencyType
())
{
if
(
Optional
.
class
==
descriptor
.
getDependencyType
())
{
return
createOptionalDependency
(
descriptor
,
requestingBeanName
);
return
createOptionalDependency
(
descriptor
,
requestingBeanName
);
}
}
...
@@ -1314,8 +1316,10 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1314,8 +1316,10 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
return
new
Jsr330Factory
().
createDependencyProvider
(
descriptor
,
requestingBeanName
);
return
new
Jsr330Factory
().
createDependencyProvider
(
descriptor
,
requestingBeanName
);
}
}
else
{
else
{
// 处理bean是否懒加载,如果懒加载,创建一个代理对象注入bean
Object
result
=
getAutowireCandidateResolver
().
getLazyResolutionProxyIfNecessary
(
Object
result
=
getAutowireCandidateResolver
().
getLazyResolutionProxyIfNecessary
(
descriptor
,
requestingBeanName
);
descriptor
,
requestingBeanName
);
// 针对一般类型的通用
if
(
result
==
null
)
{
if
(
result
==
null
)
{
result
=
doResolveDependency
(
descriptor
,
requestingBeanName
,
autowiredBeanNames
,
typeConverter
);
result
=
doResolveDependency
(
descriptor
,
requestingBeanName
,
autowiredBeanNames
,
typeConverter
);
}
}
...
@@ -1327,24 +1331,37 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1327,24 +1331,37 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
public
Object
doResolveDependency
(
DependencyDescriptor
descriptor
,
@Nullable
String
beanName
,
public
Object
doResolveDependency
(
DependencyDescriptor
descriptor
,
@Nullable
String
beanName
,
@Nullable
Set
<
String
>
autowiredBeanNames
,
@Nullable
TypeConverter
typeConverter
)
throws
BeansException
{
@Nullable
Set
<
String
>
autowiredBeanNames
,
@Nullable
TypeConverter
typeConverter
)
throws
BeansException
{
// 只有 ShortcutDependencyDescriptor 实现了 resolveShortcut 方法,返回了非空值。
// 目前版本代码只在 AutowiredFieldElement、AutowiredMethodElement 类中使用到,也即是说,
// 只有解析@Autowired、@Value注解的元素才会用到,目的是为了将解析结果缓存起来,避免重复解析
InjectionPoint
previousInjectionPoint
=
ConstructorResolver
.
setCurrentInjectionPoint
(
descriptor
);
InjectionPoint
previousInjectionPoint
=
ConstructorResolver
.
setCurrentInjectionPoint
(
descriptor
);
try
{
try
{
// 尝试获取缓存
Object
shortcut
=
descriptor
.
resolveShortcut
(
this
);
Object
shortcut
=
descriptor
.
resolveShortcut
(
this
);
if
(
shortcut
!=
null
)
{
if
(
shortcut
!=
null
)
{
// 存在缓存直接返回
return
shortcut
;
return
shortcut
;
}
}
// 获取依赖的类型
Class
<?>
type
=
descriptor
.
getDependencyType
();
Class
<?>
type
=
descriptor
.
getDependencyType
();
// 取值@Value注解中的value属性中的值,这里取出的值是未经修改的值,即带有 ${} 标签的值。
// 如果descriptor未被@Value标注,则返回null
Object
value
=
getAutowireCandidateResolver
().
getSuggestedValue
(
descriptor
);
Object
value
=
getAutowireCandidateResolver
().
getSuggestedValue
(
descriptor
);
if
(
value
!=
null
)
{
if
(
value
!=
null
)
{
// 到这里说明属性被 @Value 注解修饰了,这里是解析 @Value 注解的逻辑
// 如果value不为null,
if
(
value
instanceof
String
)
{
if
(
value
instanceof
String
)
{
// 处理占位符如${},做占位符的替换(不解析SP EL表达式)
String
strVal
=
resolveEmbeddedValue
((
String
)
value
);
String
strVal
=
resolveEmbeddedValue
((
String
)
value
);
BeanDefinition
bd
=
(
beanName
!=
null
&&
containsBean
(
beanName
)
?
BeanDefinition
bd
=
(
beanName
!=
null
&&
containsBean
(
beanName
)
?
getMergedBeanDefinition
(
beanName
)
:
null
);
getMergedBeanDefinition
(
beanName
)
:
null
);
// 解析SP EL(如#{})
value
=
evaluateBeanDefinitionString
(
strVal
,
bd
);
value
=
evaluateBeanDefinitionString
(
strVal
,
bd
);
}
}
TypeConverter
converter
=
(
typeConverter
!=
null
?
typeConverter
:
getTypeConverter
());
TypeConverter
converter
=
(
typeConverter
!=
null
?
typeConverter
:
getTypeConverter
());
try
{
try
{
// 类型转换,把解析出来的结果转成type类型
return
converter
.
convertIfNecessary
(
value
,
type
,
descriptor
.
getTypeDescriptor
());
return
converter
.
convertIfNecessary
(
value
,
type
,
descriptor
.
getTypeDescriptor
());
}
}
catch
(
UnsupportedOperationException
ex
)
{
catch
(
UnsupportedOperationException
ex
)
{
...
@@ -1355,14 +1372,18 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1355,14 +1372,18 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
}
}
// 对集合类型进行处理,包括,Array、Collection、Map。
Object
multipleBeans
=
resolveMultipleBeans
(
descriptor
,
beanName
,
autowiredBeanNames
,
typeConverter
);
Object
multipleBeans
=
resolveMultipleBeans
(
descriptor
,
beanName
,
autowiredBeanNames
,
typeConverter
);
// 如果解析出来集合类型,则直接返回
if
(
multipleBeans
!=
null
)
{
if
(
multipleBeans
!=
null
)
{
return
multipleBeans
;
return
multipleBeans
;
}
}
// 调用查找所有类型为type的实例,存放在matchingBeans <beanName, bean> (在 resolveMultipleBeans 方法中也是核心也是调用该方法)。
Map
<
String
,
Object
>
matchingBeans
=
findAutowireCandidates
(
beanName
,
type
,
descriptor
);
Map
<
String
,
Object
>
matchingBeans
=
findAutowireCandidates
(
beanName
,
type
,
descriptor
);
if
(
matchingBeans
.
isEmpty
())
{
if
(
matchingBeans
.
isEmpty
())
{
if
(
isRequired
(
descriptor
))
{
if
(
isRequired
(
descriptor
))
{
// 如果没有找到,并且bean 并标注为 required = true, 则抛出NoSuchBeanDefinitionException异常
raiseNoMatchingBeanFound
(
type
,
descriptor
.
getResolvableType
(),
descriptor
);
raiseNoMatchingBeanFound
(
type
,
descriptor
.
getResolvableType
(),
descriptor
);
}
}
return
null
;
return
null
;
...
@@ -1371,10 +1392,16 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1371,10 +1392,16 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
String
autowiredBeanName
;
String
autowiredBeanName
;
Object
instanceCandidate
;
Object
instanceCandidate
;
// 如果找到了不止一个匹配的bean,Spring 按照一定规则进行挑选
if
(
matchingBeans
.
size
()
>
1
)
{
if
(
matchingBeans
.
size
()
>
1
)
{
// 按以下顺序,找到符合条件的就直接返回
// 1. 挑选出被标识为primary的bean
// 2. 挑选标识了@Priority,且先级级最高的bean。可以不标识,一旦标识,不允许同一优先级的存在
// 3. fallback,依赖的名称与matchingBeans中任意一Key匹配
autowiredBeanName
=
determineAutowireCandidate
(
matchingBeans
,
descriptor
);
autowiredBeanName
=
determineAutowireCandidate
(
matchingBeans
,
descriptor
);
if
(
autowiredBeanName
==
null
)
{
if
(
autowiredBeanName
==
null
)
{
if
(
isRequired
(
descriptor
)
||
!
indicatesMultipleBeans
(
type
))
{
if
(
isRequired
(
descriptor
)
||
!
indicatesMultipleBeans
(
type
))
{
// 非集合类,找到了多个符合条件的Bean,抛出异常
return
descriptor
.
resolveNotUnique
(
descriptor
.
getResolvableType
(),
matchingBeans
);
return
descriptor
.
resolveNotUnique
(
descriptor
.
getResolvableType
(),
matchingBeans
);
}
}
else
{
else
{
...
@@ -1388,24 +1415,29 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1388,24 +1415,29 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
else
{
else
{
// We have exactly one match.
// We have exactly one match.
// 如果只找到了唯一匹配的元素,则直接使用
Map
.
Entry
<
String
,
Object
>
entry
=
matchingBeans
.
entrySet
().
iterator
().
next
();
Map
.
Entry
<
String
,
Object
>
entry
=
matchingBeans
.
entrySet
().
iterator
().
next
();
autowiredBeanName
=
entry
.
getKey
();
autowiredBeanName
=
entry
.
getKey
();
instanceCandidate
=
entry
.
getValue
();
instanceCandidate
=
entry
.
getValue
();
}
}
if
(
autowiredBeanNames
!=
null
)
{
if
(
autowiredBeanNames
!=
null
)
{
// 将待装配的Bean名称放入autowiredBeanNames集合里
autowiredBeanNames
.
add
(
autowiredBeanName
);
autowiredBeanNames
.
add
(
autowiredBeanName
);
}
}
if
(
instanceCandidate
instanceof
Class
)
{
if
(
instanceCandidate
instanceof
Class
)
{
// 这里又去调用 getBean 方法去获取bean
instanceCandidate
=
descriptor
.
resolveCandidate
(
autowiredBeanName
,
type
,
this
);
instanceCandidate
=
descriptor
.
resolveCandidate
(
autowiredBeanName
,
type
,
this
);
}
}
Object
result
=
instanceCandidate
;
Object
result
=
instanceCandidate
;
if
(
result
instanceof
NullBean
)
{
if
(
result
instanceof
NullBean
)
{
if
(
isRequired
(
descriptor
))
{
if
(
isRequired
(
descriptor
))
{
// 如果 result 是 NullBean类型,且 required = true,则抛出异常
raiseNoMatchingBeanFound
(
type
,
descriptor
.
getResolvableType
(),
descriptor
);
raiseNoMatchingBeanFound
(
type
,
descriptor
.
getResolvableType
(),
descriptor
);
}
}
result
=
null
;
result
=
null
;
}
}
// 类型校验,确保类型与解析出来的Bean实例能够匹配
if
(!
ClassUtils
.
isAssignableValue
(
type
,
result
))
{
if
(!
ClassUtils
.
isAssignableValue
(
type
,
result
))
{
throw
new
BeanNotOfRequiredTypeException
(
autowiredBeanName
,
type
,
instanceCandidate
.
getClass
());
throw
new
BeanNotOfRequiredTypeException
(
autowiredBeanName
,
type
,
instanceCandidate
.
getClass
());
}
}
...
@@ -1422,6 +1454,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1422,6 +1454,7 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
Class
<?>
type
=
descriptor
.
getDependencyType
();
Class
<?>
type
=
descriptor
.
getDependencyType
();
// 如果是 StreamDependencyDescriptor 类型,则返回流的形式
if
(
descriptor
instanceof
StreamDependencyDescriptor
streamDependencyDescriptor
)
{
if
(
descriptor
instanceof
StreamDependencyDescriptor
streamDependencyDescriptor
)
{
Map
<
String
,
Object
>
matchingBeans
=
findAutowireCandidates
(
beanName
,
type
,
descriptor
);
Map
<
String
,
Object
>
matchingBeans
=
findAutowireCandidates
(
beanName
,
type
,
descriptor
);
if
(
autowiredBeanNames
!=
null
)
{
if
(
autowiredBeanNames
!=
null
)
{
...
@@ -1435,7 +1468,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1435,7 +1468,9 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
}
}
return
stream
;
return
stream
;
}
}
// 如果是 数组类型
else
if
(
type
.
isArray
())
{
else
if
(
type
.
isArray
())
{
// 确定最终类型
Class
<?>
componentType
=
type
.
getComponentType
();
Class
<?>
componentType
=
type
.
getComponentType
();
ResolvableType
resolvableType
=
descriptor
.
getResolvableType
();
ResolvableType
resolvableType
=
descriptor
.
getResolvableType
();
Class
<?>
resolvedArrayType
=
resolvableType
.
resolve
(
type
);
Class
<?>
resolvedArrayType
=
resolvableType
.
resolve
(
type
);
...
@@ -1445,19 +1480,25 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
...
@@ -1445,19 +1480,25 @@ public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFacto
if
(
componentType
==
null
)
{
if
(
componentType
==
null
)
{
return
null
;
return
null
;
}
}
// 根据属性类型找到 beanFactory 中所有类型的匹配bean
// 返回值构成 : key= 匹配的beanName, value= beanName对应的实例化bean,通过 getBean(beanName)获取。
Map
<
String
,
Object
>
matchingBeans
=
findAutowireCandidates
(
beanName
,
componentType
,
Map
<
String
,
Object
>
matchingBeans
=
findAutowireCandidates
(
beanName
,
componentType
,
new
MultiElementDescriptor
(
descriptor
));
new
MultiElementDescriptor
(
descriptor
));
// 如果是未找到匹配的bean,则返回null,
if
(
matchingBeans
.
isEmpty
())
{
if
(
matchingBeans
.
isEmpty
())
{
return
null
;
return
null
;
}
}
// 保存所有适配的 beanName
if
(
autowiredBeanNames
!=
null
)
{
if
(
autowiredBeanNames
!=
null
)
{
autowiredBeanNames
.
addAll
(
matchingBeans
.
keySet
());
autowiredBeanNames
.
addAll
(
matchingBeans
.
keySet
());
}
}
// 进行类型转换,将bean 转换为对应的type 类型。
TypeConverter
converter
=
(
typeConverter
!=
null
?
typeConverter
:
getTypeConverter
());
TypeConverter
converter
=
(
typeConverter
!=
null
?
typeConverter
:
getTypeConverter
());
Object
result
=
converter
.
convertIfNecessary
(
matchingBeans
.
values
(),
resolvedArrayType
);
Object
result
=
converter
.
convertIfNecessary
(
matchingBeans
.
values
(),
resolvedArrayType
);
if
(
result
instanceof
Object
[]
array
)
{
if
(
result
instanceof
Object
[]
array
)
{
Comparator
<
Object
>
comparator
=
adaptDependencyComparator
(
matchingBeans
);
Comparator
<
Object
>
comparator
=
adaptDependencyComparator
(
matchingBeans
);
if
(
comparator
!=
null
)
{
if
(
comparator
!=
null
)
{
// 排序
Arrays
.
sort
(
array
,
comparator
);
Arrays
.
sort
(
array
,
comparator
);
}
}
}
}
...
...
spring-framework-main/spring-beans/src/main/java/org/springframework/beans/factory/support/SimpleInstantiationStrategy.java
View file @
307c9ae2
...
@@ -57,17 +57,22 @@ public class SimpleInstantiationStrategy implements InstantiationStrategy {
...
@@ -57,17 +57,22 @@ public class SimpleInstantiationStrategy implements InstantiationStrategy {
@Override
@Override
public
Object
instantiate
(
RootBeanDefinition
bd
,
@Nullable
String
beanName
,
BeanFactory
owner
)
{
public
Object
instantiate
(
RootBeanDefinition
bd
,
@Nullable
String
beanName
,
BeanFactory
owner
)
{
// Don't override the class with CGLIB if no overrides.
// Don't override the class with CGLIB if no overrides.
// 如果当前bean中的方法没有都没有被重写,则直接反射就好了。不需要使用cglib 来进行代理
if
(!
bd
.
hasMethodOverrides
())
{
if
(!
bd
.
hasMethodOverrides
())
{
Constructor
<?>
constructorToUse
;
Constructor
<?>
constructorToUse
;
synchronized
(
bd
.
constructorArgumentLock
)
{
synchronized
(
bd
.
constructorArgumentLock
)
{
// 尝试获取已经解析成功缓存的 构造函数
constructorToUse
=
(
Constructor
<?>)
bd
.
resolvedConstructorOrFactoryMethod
;
constructorToUse
=
(
Constructor
<?>)
bd
.
resolvedConstructorOrFactoryMethod
;
if
(
constructorToUse
==
null
)
{
if
(
constructorToUse
==
null
)
{
// 没有缓存则自己指定无参构造函数
final
Class
<?>
clazz
=
bd
.
getBeanClass
();
final
Class
<?>
clazz
=
bd
.
getBeanClass
();
if
(
clazz
.
isInterface
())
{
if
(
clazz
.
isInterface
())
{
throw
new
BeanInstantiationException
(
clazz
,
"Specified class is an interface"
);
throw
new
BeanInstantiationException
(
clazz
,
"Specified class is an interface"
);
}
}
try
{
try
{
// 返回符合参数类型的构造函数(这里是无参构造函数,所以并没有传递参数)
constructorToUse
=
clazz
.
getDeclaredConstructor
();
constructorToUse
=
clazz
.
getDeclaredConstructor
();
// 指定无参构造函数
bd
.
resolvedConstructorOrFactoryMethod
=
constructorToUse
;
bd
.
resolvedConstructorOrFactoryMethod
=
constructorToUse
;
}
}
catch
(
Throwable
ex
)
{
catch
(
Throwable
ex
)
{
...
@@ -75,10 +80,12 @@ public class SimpleInstantiationStrategy implements InstantiationStrategy {
...
@@ -75,10 +80,12 @@ public class SimpleInstantiationStrategy implements InstantiationStrategy {
}
}
}
}
}
}
// 通过反射创建 bean
return
BeanUtils
.
instantiateClass
(
constructorToUse
);
return
BeanUtils
.
instantiateClass
(
constructorToUse
);
}
}
else
{
else
{
// Must generate CGLIB subclass.
// Must generate CGLIB subclass.
// 如果有方法被重写了,则使用cglib 动态代理
return
instantiateWithMethodInjection
(
bd
,
beanName
,
owner
);
return
instantiateWithMethodInjection
(
bd
,
beanName
,
owner
);
}
}
}
}
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/AbstractApplicationContext.java
View file @
307c9ae2
...
@@ -555,43 +555,44 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
...
@@ -555,43 +555,44 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
synchronized
(
this
.
startupShutdownMonitor
)
{
synchronized
(
this
.
startupShutdownMonitor
)
{
StartupStep
contextRefresh
=
this
.
applicationStartup
.
start
(
"spring.context.refresh"
);
StartupStep
contextRefresh
=
this
.
applicationStartup
.
start
(
"spring.context.refresh"
);
//
Prepare this context for refreshing.
//
1,准备刷新上下文环境
prepareRefresh
();
prepareRefresh
();
//
Tell the subclass to refresh the internal bean factory.
//
2,初始化BeanFactory,并进行xml文件读取
ConfigurableListableBeanFactory
beanFactory
=
obtainFreshBeanFactory
();
ConfigurableListableBeanFactory
beanFactory
=
obtainFreshBeanFactory
();
// Prepare the bean factory for use in this context.
// 3,对BeanFactory进行各种功能填充
// 这个时候开始对上下文进行设置
prepareBeanFactory
(
beanFactory
);
prepareBeanFactory
(
beanFactory
);
try
{
try
{
//
Allows post-processing of the bean factory in context subclasses.
//
4,子类覆盖方法做额外的处理
postProcessBeanFactory
(
beanFactory
);
postProcessBeanFactory
(
beanFactory
);
StartupStep
beanPostProcess
=
this
.
applicationStartup
.
start
(
"spring.context.beans.post-process"
);
StartupStep
beanPostProcess
=
this
.
applicationStartup
.
start
(
"spring.context.beans.post-process"
);
//
Invoke factory processors registered as beans in the context.
//
5,激活各种 BeanFactory 处理器
invokeBeanFactoryPostProcessors
(
beanFactory
);
invokeBeanFactoryPostProcessors
(
beanFactory
);
//
Register bean processors that intercept bean creation.
//
6,注册拦截 Bean 创建的 Bean 处理器。(只是注册,真正调用在getBean)
registerBeanPostProcessors
(
beanFactory
);
registerBeanPostProcessors
(
beanFactory
);
beanPostProcess
.
end
();
beanPostProcess
.
end
();
//
Initialize message source for this context.
//
7,为上下文初始化Message源,即不同语言的消息体,国际化处理
initMessageSource
();
initMessageSource
();
//
Initialize event multicaster for this context.
//
8,;初始化应用消息广播器,并放入applicationEventMulticaster 的 bean 中
initApplicationEventMulticaster
();
initApplicationEventMulticaster
();
//
Initialize other special beans in specific context subclasses.
//
9,留给子类来初始化其他的 Bean
onRefresh
();
onRefresh
();
//
Check for listener beans and register them.
//
10,在所有注册的 Bean 中查找 Listener Bean,注册到消息广播中
registerListeners
();
registerListeners
();
//
Instantiate all remaining (non-lazy-init) singletons.
//
11,初始化剩下的单实例(非惰性的)
finishBeanFactoryInitialization
(
beanFactory
);
finishBeanFactoryInitialization
(
beanFactory
);
//
Last step: publish corresponding event.
//
12,完成刷新过程, 通知生命周期处理器 LifecycleProcessor 刷新过程同时发出 ContextRefreshEvent通知别人
finishRefresh
();
finishRefresh
();
}
}
...
@@ -640,6 +641,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
...
@@ -640,6 +641,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
}
}
// Initialize any placeholder property sources in the context environment.
// Initialize any placeholder property sources in the context environment.
// 留给子类处理
initPropertySources
();
initPropertySources
();
// Validate that all properties marked as required are resolvable:
// Validate that all properties marked as required are resolvable:
...
@@ -677,7 +679,9 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
...
@@ -677,7 +679,9 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
* @see #getBeanFactory()
* @see #getBeanFactory()
*/
*/
protected
ConfigurableListableBeanFactory
obtainFreshBeanFactory
()
{
protected
ConfigurableListableBeanFactory
obtainFreshBeanFactory
()
{
// 初始化 BeanFactory ,并进行XML文件读取,得到BeanFactory存储在当前实体类的属性中
refreshBeanFactory
();
refreshBeanFactory
();
// 返回当前的BeanFactory属性
return
getBeanFactory
();
return
getBeanFactory
();
}
}
...
@@ -688,14 +692,21 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
...
@@ -688,14 +692,21 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
*/
*/
protected
void
prepareBeanFactory
(
ConfigurableListableBeanFactory
beanFactory
)
{
protected
void
prepareBeanFactory
(
ConfigurableListableBeanFactory
beanFactory
)
{
// Tell the internal bean factory to use the context's class loader etc.
// Tell the internal bean factory to use the context's class loader etc.
// 设置 BeanFactory 的 ClassLoader 为当前 context 的 classLoader
beanFactory
.
setBeanClassLoader
(
getClassLoader
());
beanFactory
.
setBeanClassLoader
(
getClassLoader
());
// 设置 BeanFactory 的表达式处理器(SpE),Spring3增加
if
(!
shouldIgnoreSpel
)
{
if
(!
shouldIgnoreSpel
)
{
beanFactory
.
setBeanExpressionResolver
(
new
StandardBeanExpressionResolver
(
beanFactory
.
getBeanClassLoader
()));
beanFactory
.
setBeanExpressionResolver
(
new
StandardBeanExpressionResolver
(
beanFactory
.
getBeanClassLoader
()));
}
}
// 设置属性注册解析器PropertyEditor:String 变为 Date类型
beanFactory
.
addPropertyEditorRegistrar
(
new
ResourceEditorRegistrar
(
this
,
getEnvironment
()));
beanFactory
.
addPropertyEditorRegistrar
(
new
ResourceEditorRegistrar
(
this
,
getEnvironment
()));
// Configure the bean factory with context callbacks.
// Configure the bean factory with context callbacks.
// 添加ApplicationContextAwareProcessor,只有before,是aware接口的话,给bean设置对应的 aware 属性
// BeanPostProcessor 和 BeanFactoryPostProcessor
beanFactory
.
addBeanPostProcessor
(
new
ApplicationContextAwareProcessor
(
this
));
beanFactory
.
addBeanPostProcessor
(
new
ApplicationContextAwareProcessor
(
this
));
// aware接口已经被设置,所以这里要忽略依赖注入
beanFactory
.
ignoreDependencyInterface
(
EnvironmentAware
.
class
);
beanFactory
.
ignoreDependencyInterface
(
EnvironmentAware
.
class
);
beanFactory
.
ignoreDependencyInterface
(
EmbeddedValueResolverAware
.
class
);
beanFactory
.
ignoreDependencyInterface
(
EmbeddedValueResolverAware
.
class
);
beanFactory
.
ignoreDependencyInterface
(
ResourceLoaderAware
.
class
);
beanFactory
.
ignoreDependencyInterface
(
ResourceLoaderAware
.
class
);
...
@@ -706,22 +717,27 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
...
@@ -706,22 +717,27 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
// BeanFactory interface not registered as resolvable type in a plain factory.
// BeanFactory interface not registered as resolvable type in a plain factory.
// MessageSource registered (and found for autowiring) as a bean.
// MessageSource registered (and found for autowiring) as a bean.
// 将下列类注册为可解析类型
beanFactory
.
registerResolvableDependency
(
BeanFactory
.
class
,
beanFactory
);
beanFactory
.
registerResolvableDependency
(
BeanFactory
.
class
,
beanFactory
);
beanFactory
.
registerResolvableDependency
(
ResourceLoader
.
class
,
this
);
beanFactory
.
registerResolvableDependency
(
ResourceLoader
.
class
,
this
);
beanFactory
.
registerResolvableDependency
(
ApplicationEventPublisher
.
class
,
this
);
beanFactory
.
registerResolvableDependency
(
ApplicationEventPublisher
.
class
,
this
);
beanFactory
.
registerResolvableDependency
(
ApplicationContext
.
class
,
this
);
beanFactory
.
registerResolvableDependency
(
ApplicationContext
.
class
,
this
);
// Register early post-processor for detecting inner beans as ApplicationListeners.
// Register early post-processor for detecting inner beans as ApplicationListeners.
// 用后置处理器注册为监听器 PropertyPlaceholderConfigure
beanFactory
.
addBeanPostProcessor
(
new
ApplicationListenerDetector
(
this
));
beanFactory
.
addBeanPostProcessor
(
new
ApplicationListenerDetector
(
this
));
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// Detect a LoadTimeWeaver and prepare for weaving, if found.
// 如果当前BeanFactory包含loadTimeWeaver Bean,说明存在类加载期织入AspectJ,
// 则把当前BeanFactory交给类加载期BeanPostProcessor实现类LoadTimeWeaverAwareProcessor来处理,
// 从而实现类加载期织入AspectJ的目的。
if
(!
NativeDetector
.
inNativeImage
()
&&
beanFactory
.
containsBean
(
LOAD_TIME_WEAVER_BEAN_NAME
))
{
if
(!
NativeDetector
.
inNativeImage
()
&&
beanFactory
.
containsBean
(
LOAD_TIME_WEAVER_BEAN_NAME
))
{
beanFactory
.
addBeanPostProcessor
(
new
LoadTimeWeaverAwareProcessor
(
beanFactory
));
beanFactory
.
addBeanPostProcessor
(
new
LoadTimeWeaverAwareProcessor
(
beanFactory
));
// Set a temporary ClassLoader for type matching.
// Set a temporary ClassLoader for type matching.
beanFactory
.
setTempClassLoader
(
new
ContextTypeMatchClassLoader
(
beanFactory
.
getBeanClassLoader
()));
beanFactory
.
setTempClassLoader
(
new
ContextTypeMatchClassLoader
(
beanFactory
.
getBeanClassLoader
()));
}
}
//
Register default environment beans.
//
添加默认系统环境bean
if
(!
beanFactory
.
containsLocalBean
(
ENVIRONMENT_BEAN_NAME
))
{
if
(!
beanFactory
.
containsLocalBean
(
ENVIRONMENT_BEAN_NAME
))
{
beanFactory
.
registerSingleton
(
ENVIRONMENT_BEAN_NAME
,
getEnvironment
());
beanFactory
.
registerSingleton
(
ENVIRONMENT_BEAN_NAME
,
getEnvironment
());
}
}
...
@@ -752,6 +768,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
...
@@ -752,6 +768,7 @@ public abstract class AbstractApplicationContext extends DefaultResourceLoader
* <p>Must be called before singleton instantiation.
* <p>Must be called before singleton instantiation.
*/
*/
protected
void
invokeBeanFactoryPostProcessors
(
ConfigurableListableBeanFactory
beanFactory
)
{
protected
void
invokeBeanFactoryPostProcessors
(
ConfigurableListableBeanFactory
beanFactory
)
{
// 核心方法
PostProcessorRegistrationDelegate
.
invokeBeanFactoryPostProcessors
(
beanFactory
,
getBeanFactoryPostProcessors
());
PostProcessorRegistrationDelegate
.
invokeBeanFactoryPostProcessors
(
beanFactory
,
getBeanFactoryPostProcessors
());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/AbstractRefreshableApplicationContext.java
View file @
307c9ae2
...
@@ -119,14 +119,19 @@ public abstract class AbstractRefreshableApplicationContext extends AbstractAppl
...
@@ -119,14 +119,19 @@ public abstract class AbstractRefreshableApplicationContext extends AbstractAppl
*/
*/
@Override
@Override
protected
final
void
refreshBeanFactory
()
throws
BeansException
{
protected
final
void
refreshBeanFactory
()
throws
BeansException
{
// 如果有bean工厂,销毁bean以及关闭bean工厂
if
(
hasBeanFactory
())
{
if
(
hasBeanFactory
())
{
destroyBeans
();
destroyBeans
();
closeBeanFactory
();
closeBeanFactory
();
}
}
try
{
try
{
// 创建 DefaultListableBeanFactory
DefaultListableBeanFactory
beanFactory
=
createBeanFactory
();
DefaultListableBeanFactory
beanFactory
=
createBeanFactory
();
// 为了序列化指定 id,需要的话,让这个 BeanFactory 从 id 反序列化到 BeanFactory 对象
beanFactory
.
setSerializationId
(
getId
());
beanFactory
.
setSerializationId
(
getId
());
// 定制BeanFactory,设置相关属性,包括是否允许 覆盖同名称的不同定义的对象, 是否允许 循环依赖
customizeBeanFactory
(
beanFactory
);
customizeBeanFactory
(
beanFactory
);
// 初始化 DocumentReader 并进行 Xml 文件读取并解析
loadBeanDefinitions
(
beanFactory
);
loadBeanDefinitions
(
beanFactory
);
this
.
beanFactory
=
beanFactory
;
this
.
beanFactory
=
beanFactory
;
}
}
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/ApplicationContextAwareProcessor.java
View file @
307c9ae2
...
@@ -75,6 +75,7 @@ class ApplicationContextAwareProcessor implements BeanPostProcessor {
...
@@ -75,6 +75,7 @@ class ApplicationContextAwareProcessor implements BeanPostProcessor {
@Override
@Override
@Nullable
@Nullable
public
Object
postProcessBeforeInitialization
(
Object
bean
,
String
beanName
)
throws
BeansException
{
public
Object
postProcessBeforeInitialization
(
Object
bean
,
String
beanName
)
throws
BeansException
{
// 不是 Aware 直接返回
if
(!(
bean
instanceof
EnvironmentAware
||
bean
instanceof
EmbeddedValueResolverAware
||
if
(!(
bean
instanceof
EnvironmentAware
||
bean
instanceof
EmbeddedValueResolverAware
||
bean
instanceof
ResourceLoaderAware
||
bean
instanceof
ApplicationEventPublisherAware
||
bean
instanceof
ResourceLoaderAware
||
bean
instanceof
ApplicationEventPublisherAware
||
bean
instanceof
MessageSourceAware
||
bean
instanceof
ApplicationContextAware
||
bean
instanceof
MessageSourceAware
||
bean
instanceof
ApplicationContextAware
||
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/ClassPathXmlApplicationContext.java
View file @
307c9ae2
...
@@ -75,6 +75,7 @@ public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContex
...
@@ -75,6 +75,7 @@ public class ClassPathXmlApplicationContext extends AbstractXmlApplicationContex
super
(
parent
);
super
(
parent
);
}
}
// TODO: 2022/8/9 applicationContext在这儿
/**
/**
* Create a new ClassPathXmlApplicationContext, loading the definitions
* Create a new ClassPathXmlApplicationContext, loading the definitions
* from the given XML file and automatically refreshing the context.
* from the given XML file and automatically refreshing the context.
...
...
spring-framework-main/spring-context/src/main/java/org/springframework/context/support/PostProcessorRegistrationDelegate.java
View file @
307c9ae2
...
@@ -79,14 +79,24 @@ final class PostProcessorRegistrationDelegate {
...
@@ -79,14 +79,24 @@ final class PostProcessorRegistrationDelegate {
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// https://github.com/spring-projects/spring-framework/issues?q=PostProcessorRegistrationDelegate+is%3Aclosed+label%3A%22status%3A+declined%22
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 如果有的话,首先调用 BeanDefinitionRegistryPostProcessors。
Set
<
String
>
processedBeans
=
new
HashSet
<>();
Set
<
String
>
processedBeans
=
new
HashSet
<>();
// 1.判断 beanFactory 是否为 BeanDefinitionRegistry,beanFactory 为 DefaultListableBeanFactory,
// 而 DefaultListableBeanFactory 实现了 BeanDefinitionRegistry 接口,因此这边为 true
if
(
beanFactory
instanceof
BeanDefinitionRegistry
registry
)
{
if
(
beanFactory
instanceof
BeanDefinitionRegistry
registry
)
{
// 用于存放普通的 BeanFactoryPostProcessor
List
<
BeanFactoryPostProcessor
>
regularPostProcessors
=
new
ArrayList
<>();
List
<
BeanFactoryPostProcessor
>
regularPostProcessors
=
new
ArrayList
<>();
// 用于存放 BeanDefinitionRegistryPostProcessor
List
<
BeanDefinitionRegistryPostProcessor
>
registryProcessors
=
new
ArrayList
<>();
List
<
BeanDefinitionRegistryPostProcessor
>
registryProcessors
=
new
ArrayList
<>();
// 2.首先处理入参中的 beanFactoryPostProcessors
// 遍历所有的 beanFactoryPostProcessors,
// 将 BeanDefinitionRegistryPostProcessor 和普通 BeanFactoryPostProcessor 区分开
for
(
BeanFactoryPostProcessor
postProcessor
:
beanFactoryPostProcessors
)
{
for
(
BeanFactoryPostProcessor
postProcessor
:
beanFactoryPostProcessors
)
{
// 添加是为了用于最后执行 postProcessBeanFactory 方法
if
(
postProcessor
instanceof
BeanDefinitionRegistryPostProcessor
registryProcessor
)
{
if
(
postProcessor
instanceof
BeanDefinitionRegistryPostProcessor
registryProcessor
)
{
// 添加且直接执行
registryProcessor
.
postProcessBeanDefinitionRegistry
(
registry
);
registryProcessor
.
postProcessBeanDefinitionRegistry
(
registry
);
registryProcessors
.
add
(
registryProcessor
);
registryProcessors
.
add
(
registryProcessor
);
}
}
...
@@ -99,25 +109,41 @@ final class PostProcessorRegistrationDelegate {
...
@@ -99,25 +109,41 @@ final class PostProcessorRegistrationDelegate {
// uninitialized to let the bean factory post-processors apply to them!
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// PriorityOrdered, Ordered, and the rest.
// 用于保存本次要执行的BeanDefinitionRegistryPostProcessor
List
<
BeanDefinitionRegistryPostProcessor
>
currentRegistryProcessors
=
new
ArrayList
<>();
List
<
BeanDefinitionRegistryPostProcessor
>
currentRegistryProcessors
=
new
ArrayList
<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 3.调用所有实现 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor 实现类
// 找出所有实现 BeanDefinitionRegistryPostProcessor 接口的 Bean 的 beanName
String
[]
postProcessorNames
=
String
[]
postProcessorNames
=
beanFactory
.
getBeanNamesForType
(
BeanDefinitionRegistryPostProcessor
.
class
,
true
,
false
);
beanFactory
.
getBeanNamesForType
(
BeanDefinitionRegistryPostProcessor
.
class
,
true
,
false
);
// 遍历 postProcessorNames
for
(
String
ppName
:
postProcessorNames
)
{
for
(
String
ppName
:
postProcessorNames
)
{
// 校验是否实现了PriorityOrdered接口
if
(
beanFactory
.
isTypeMatch
(
ppName
,
PriorityOrdered
.
class
))
{
if
(
beanFactory
.
isTypeMatch
(
ppName
,
PriorityOrdered
.
class
))
{
// 获取ppName对应的bean实例, 添加到currentRegistryProcessors中,
currentRegistryProcessors
.
add
(
beanFactory
.
getBean
(
ppName
,
BeanDefinitionRegistryPostProcessor
.
class
));
currentRegistryProcessors
.
add
(
beanFactory
.
getBean
(
ppName
,
BeanDefinitionRegistryPostProcessor
.
class
));
// 将要被执行的加入processedBeans,避免后续重复执行
processedBeans
.
add
(
ppName
);
processedBeans
.
add
(
ppName
);
}
}
}
}
// 进行排序(根据是否实现PriorityOrdered、Ordered接口和order值来排序)
sortPostProcessors
(
currentRegistryProcessors
,
beanFactory
);
sortPostProcessors
(
currentRegistryProcessors
,
beanFactory
);
// 添加到registryProcessors(用于最后执行postProcessBeanFactory方法)
registryProcessors
.
addAll
(
currentRegistryProcessors
);
registryProcessors
.
addAll
(
currentRegistryProcessors
);
// 遍历currentRegistryProcessors, 执行postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors
(
currentRegistryProcessors
,
registry
,
beanFactory
.
getApplicationStartup
());
invokeBeanDefinitionRegistryPostProcessors
(
currentRegistryProcessors
,
registry
,
beanFactory
.
getApplicationStartup
());
// 执行完毕后, 清空currentRegistryProcessors
currentRegistryProcessors
.
clear
();
currentRegistryProcessors
.
clear
();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 4.调用所有实现了 Ordered 接口的 BeanDefinitionRegistryPostProcessor 实现类(过程跟上面的步骤3基本一样)
// 找出所有实现 BeanDefinitionRegistryPostProcessor 接口的类,
// 这边重复查找是因为执行完上面的BeanDefinitionRegistryPostProcessor,
// 可能会新增了其他的BeanDefinitionRegistryPostProcessor, 因此需要重新查找
postProcessorNames
=
beanFactory
.
getBeanNamesForType
(
BeanDefinitionRegistryPostProcessor
.
class
,
true
,
false
);
postProcessorNames
=
beanFactory
.
getBeanNamesForType
(
BeanDefinitionRegistryPostProcessor
.
class
,
true
,
false
);
for
(
String
ppName
:
postProcessorNames
)
{
for
(
String
ppName
:
postProcessorNames
)
{
// 多加一条,要求没有执行过
if
(!
processedBeans
.
contains
(
ppName
)
&&
beanFactory
.
isTypeMatch
(
ppName
,
Ordered
.
class
))
{
if
(!
processedBeans
.
contains
(
ppName
)
&&
beanFactory
.
isTypeMatch
(
ppName
,
Ordered
.
class
))
{
currentRegistryProcessors
.
add
(
beanFactory
.
getBean
(
ppName
,
BeanDefinitionRegistryPostProcessor
.
class
));
currentRegistryProcessors
.
add
(
beanFactory
.
getBean
(
ppName
,
BeanDefinitionRegistryPostProcessor
.
class
));
processedBeans
.
add
(
ppName
);
processedBeans
.
add
(
ppName
);
...
@@ -129,6 +155,7 @@ final class PostProcessorRegistrationDelegate {
...
@@ -129,6 +155,7 @@ final class PostProcessorRegistrationDelegate {
currentRegistryProcessors
.
clear
();
currentRegistryProcessors
.
clear
();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 5.最后, 调用所有剩下的BeanDefinitionRegistryPostProcessors
boolean
reiterate
=
true
;
boolean
reiterate
=
true
;
while
(
reiterate
)
{
while
(
reiterate
)
{
reiterate
=
false
;
reiterate
=
false
;
...
@@ -147,7 +174,10 @@ final class PostProcessorRegistrationDelegate {
...
@@ -147,7 +174,10 @@ final class PostProcessorRegistrationDelegate {
}
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 6.调用所有 BeanDefinitionRegistryPostProcessor 的 postProcessBeanFactory 方法
// (BeanDefinitionRegistryPostProcessor继承自BeanFactoryPostProcessor)
invokeBeanFactoryPostProcessors
(
registryProcessors
,
beanFactory
);
invokeBeanFactoryPostProcessors
(
registryProcessors
,
beanFactory
);
// 7.最后, 调用入参 beanFactoryPostProcessors 中的普通 BeanFactoryPostProcessor 的 postProcessBeanFactory 方法
invokeBeanFactoryPostProcessors
(
regularPostProcessors
,
beanFactory
);
invokeBeanFactoryPostProcessors
(
regularPostProcessors
,
beanFactory
);
}
}
...
@@ -158,15 +188,23 @@ final class PostProcessorRegistrationDelegate {
...
@@ -158,15 +188,23 @@ final class PostProcessorRegistrationDelegate {
// Do not initialize FactoryBeans here: We need to leave all regular beans
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// uninitialized to let the bean factory post-processors apply to them!
// 到这里, 入参 beanFactoryPostProcessors 和容器中的所有 BeanDefinitionRegistryPostProcessor 已经全部处理完毕,
// 下面开始处理容器中的所有 BeanFactoryPostProcessor
// 8.找出所有实现BeanFactoryPostProcessor接口的类
String
[]
postProcessorNames
=
String
[]
postProcessorNames
=
beanFactory
.
getBeanNamesForType
(
BeanFactoryPostProcessor
.
class
,
true
,
false
);
beanFactory
.
getBeanNamesForType
(
BeanFactoryPostProcessor
.
class
,
true
,
false
);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
// Ordered, and the rest.
// 用于存放实现了 PriorityOrdered 接口的 BeanFactoryPostProcessor
List
<
BeanFactoryPostProcessor
>
priorityOrderedPostProcessors
=
new
ArrayList
<>();
List
<
BeanFactoryPostProcessor
>
priorityOrderedPostProcessors
=
new
ArrayList
<>();
// 用于存放实现了Ordered接口的BeanFactoryPostProcessor的beanName
List
<
String
>
orderedPostProcessorNames
=
new
ArrayList
<>();
List
<
String
>
orderedPostProcessorNames
=
new
ArrayList
<>();
// 普通的
List
<
String
>
nonOrderedPostProcessorNames
=
new
ArrayList
<>();
List
<
String
>
nonOrderedPostProcessorNames
=
new
ArrayList
<>();
// 遍历postProcessorNames, 将 BeanFactoryPostProcessor 按实现 PriorityOrdered、实现Ordered接口、普通三种区分开
for
(
String
ppName
:
postProcessorNames
)
{
for
(
String
ppName
:
postProcessorNames
)
{
// 已经执行的跳过
if
(
processedBeans
.
contains
(
ppName
))
{
if
(
processedBeans
.
contains
(
ppName
))
{
// skip - already processed in first phase above
// skip - already processed in first phase above
}
}
...
@@ -182,6 +220,8 @@ final class PostProcessorRegistrationDelegate {
...
@@ -182,6 +220,8 @@ final class PostProcessorRegistrationDelegate {
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// 9.调用所有实现 PriorityOrdered 接口的 BeanFactoryPostProcessor
// 对 priorityOrderedPostProcessors 排序
sortPostProcessors
(
priorityOrderedPostProcessors
,
beanFactory
);
sortPostProcessors
(
priorityOrderedPostProcessors
,
beanFactory
);
invokeBeanFactoryPostProcessors
(
priorityOrderedPostProcessors
,
beanFactory
);
invokeBeanFactoryPostProcessors
(
priorityOrderedPostProcessors
,
beanFactory
);
...
@@ -202,6 +242,8 @@ final class PostProcessorRegistrationDelegate {
...
@@ -202,6 +242,8 @@ final class PostProcessorRegistrationDelegate {
// Clear cached merged bean definitions since the post-processors might have
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
// modified the original metadata, e.g. replacing placeholders in values...
// 12.清除元数据缓存(mergedBeanDefinitions、allBeanNamesByType、singletonBeanNamesByType),
// 因为后处理器可能已经修改了原始元数据,例如, 替换值中的占位符...
beanFactory
.
clearMetadataCache
();
beanFactory
.
clearMetadataCache
();
}
}
...
...
spring-framework-main/spring-web/src/main/java/org/springframework/web/context/support/XmlWebApplicationContext.java
View file @
307c9ae2
...
@@ -80,17 +80,21 @@ public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationC
...
@@ -80,17 +80,21 @@ public class XmlWebApplicationContext extends AbstractRefreshableWebApplicationC
@Override
@Override
protected
void
loadBeanDefinitions
(
DefaultListableBeanFactory
beanFactory
)
throws
BeansException
,
IOException
{
protected
void
loadBeanDefinitions
(
DefaultListableBeanFactory
beanFactory
)
throws
BeansException
,
IOException
{
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
// 为指定beanFactory创建XmlBeanDefinitionReader(加载解析bean)
XmlBeanDefinitionReader
beanDefinitionReader
=
new
XmlBeanDefinitionReader
(
beanFactory
);
XmlBeanDefinitionReader
beanDefinitionReader
=
new
XmlBeanDefinitionReader
(
beanFactory
);
// Configure the bean definition reader with this context's
// Configure the bean definition reader with this context's
// resource loading environment.
// resource loading environment.
// 对beanDefinitionReader进行环境变量的设置
beanDefinitionReader
.
setEnvironment
(
getEnvironment
());
beanDefinitionReader
.
setEnvironment
(
getEnvironment
());
beanDefinitionReader
.
setResourceLoader
(
this
);
beanDefinitionReader
.
setResourceLoader
(
this
);
beanDefinitionReader
.
setEntityResolver
(
new
ResourceEntityResolver
(
this
));
beanDefinitionReader
.
setEntityResolver
(
new
ResourceEntityResolver
(
this
));
// Allow a subclass to provide custom initialization of the reader,
// Allow a subclass to provide custom initialization of the reader,
// then proceed with actually loading the bean definitions.
// then proceed with actually loading the bean definitions.
// 对beanDefinitionReader进行设置,空方法
initBeanDefinitionReader
(
beanDefinitionReader
);
initBeanDefinitionReader
(
beanDefinitionReader
);
// 设置loadBeanDefinitions的配置文件
loadBeanDefinitions
(
beanDefinitionReader
);
loadBeanDefinitions
(
beanDefinitionReader
);
}
}
...
...
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment