Spring源码解析六 (Bean的初始化)
目录
在前面分析IOC容器时有说到, 在IOC容器初始化结束后, 会开始初始化非延迟加载的单例Bean, 对于其他Bean则会在调用getBean()方法时去实例化返回;
对于整个IOC容器Bean的初始化流程如下:
由流程图可以看到, Bean实例化的主要逻辑在AbstractBeanFactory#doGetBean方法和AbstractAutowireCapableBeanFactory#doCreateBean方法中; 顾名思义, doGetBean方法是获取bean而doCreateBean方法时创建bean; 接下来开始分析bean的实例化过程;
AbstractBeanFactory#getBean
==> AbstractBeanFactory#doGetBean实现:
protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
@Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
/**
* 1.提取对应的beanName
*/
final String beanName = transformedBeanName(name);
Object bean;
/**
* 2.直接尝试从缓存中获取或者从singletonFactories中的ObjectFactory中获取(从缓存中获取单例bean)
*
* 检查缓存中或者实例工厂中是否有对应的实例
* 为什么首先使用这段代码呢?
* 因为在创建单例bean的时候会存在依赖注入的情况,而在创建依赖的时候为了避免循环依赖,
* spring创建bean的原则是不等bean创建完成就会将创建bean的objectFactory提早曝光
* 也就是将ObjectFactory加入到缓存中,一旦下一个bean创建的时候需要依赖上一个bean则直接使用ObjectFactory
*/
Object sharedInstance = getSingleton(beanName);
//如果从缓存中获取到
if (sharedInstance != null && args == null) {
//日志记录
if (logger.isDebugEnabled()) {
if (isSingletonCurrentlyInCreation(beanName)) {
logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
"' that is not fully initialized yet - a consequence of a circular reference");
}
else {
logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
}
}
/**
* 3.返回对应的实例,有时候存在诸如FactoryBean的情况并不是直接返回实例本身而是返回指定方法的实例
*
* 无论是直接取单例的bean,还是创建单例、多例、自定义生命周期的bean,
* 都会经过bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);这个方法
* 主要是由于存在 诸如FactoryBean的情况并不是直接返回实例本身而是返回指定方法的实例 的情况
*/
bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
}
//如果没有在缓存中获取到
else {
/**
* 4.首先进行原型模式的依赖检查,只有在单例情况下才会尝试解决循环依赖,如果是原型模式,则抛出异常
*
* 注意:
* (1)只有在单例情况下才会尝试解决循环依赖;
* (2)原型模式情况下,如果存在A中有B的属性,B中有A的属性,那么当依赖注入的时候,
* 就会产生当A还未创建完成的时候因为对于B的创建再次返回创建A,造成循环依赖,
* 对于此种情况Spring选择抛出异常,而不是解决循环依赖;
*
* 因为isPrototypeCurrentlyInCreation(beanName)为true, 说明此时正在创建的原型类型的bean已经存在于正在创建的集合中,
* 此时是对同一个bean的第二次创建, 然而第一次创建还未完成, 说明出现了循环依赖, 抛出异常;
* 如果该bean是原型, 但是这是第一次创建, 可以正常向下执行
*
*/
if (isPrototypeCurrentlyInCreation(beanName)) {
throw new BeanCurrentlyInCreationException(beanName);
}
/**
* 5.检查该beanName信息是否存在于工厂中
* !containsBeanDefinition(beanName):如果beanDefinitionMap中也就是当前加载的XML配置文件所生成的在类中不包括beanName,则尝试从parentBeanFactory中检测
*
* 注意:
* 如果原型模式的bean中出现循环依赖,那么就会抛出异常,并且程序将不再向下执行,如果原型模式的bean是第一次创建, 那么可以继续执行
* 如果是单例模式中有循环依赖,那么在后面创建单例模式的的bean时会针对循环依赖进行解决
*/
BeanFactory parentBeanFactory = getParentBeanFactory();
if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
// Not found -> check parent.
//获取beanName
String nameToLookup = originalBeanName(name);
if (parentBeanFactory instanceof AbstractBeanFactory) {
return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
nameToLookup, requiredType, args, typeCheckOnly);
}
//递归到BeanFactory中寻找
else if (args != null) {
// Delegation to parent with explicit args.
//递归调用父Bean工厂的getBean(String name, Object... args)
return (T) parentBeanFactory.getBean(nameToLookup, args);
}
else {
// No args -> delegate to standard getBean method.
//递归调用父Bean工厂的getBean(String name, Class<T> requiredType)
return parentBeanFactory.getBean(nameToLookup, requiredType);
}
}
//如果不是仅仅做类型检查而是创建创建bean,这里要进行记录
if (!typeCheckOnly) {
markBeanAsCreated(beanName);
}
try {
/**
* 6. 将存储XML配置文件的GerenicBeanDefinition转换为RootBeanDefintion,
* 转换的同时如果父类bean不为空的话,则会合并父类的属性
*/
final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
checkMergedBeanDefinition(mbd, beanName, args);
/**
* 7.保证当前bean所依赖的bean的初始化(这里并不是循环依赖)
* dependsOn属性是在配置文件中设置的 <bean name="dao" class="" depends-on="database" ></bean>
*/
String[] dependsOn = mbd.getDependsOn();
//若存在依赖则需要递归实例化依赖的bean
if (dependsOn != null) {
for (String dep : dependsOn) {
if (isDependent(beanName, dep)) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
}
//注册依赖的bean信息
registerDependentBean(dep, beanName);
try {
//实例化依赖的bean(循环调用getbean()方法)
getBean(dep);
}
catch (NoSuchBeanDefinitionException ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"'" + beanName + "' depends on missing bean '" + dep + "'", ex);
}
}
}
/**
* 8. 创建bean实例
* 当所依赖的bean被实例化后,接下来就可以根据scope的不同来创建bean了
*/
/**
* 8.1 单例模式的创建 (通过匿名内部类进行创建)
*/
if (mbd.isSingleton()) {
/**
* 单例模式下根据beanName创建bean实例
*/
sharedInstance = getSingleton(beanName, () -> {
try {
/**
* {@link AbstractAutowireCapableBeanFactory#createBean(String,RootBeanDefinition,Object[])}
*/
return createBean(beanName, mbd, args);
}
catch (BeansException ex) {
// Explicitly remove instance from singleton cache: It might have been put there
// eagerly by the creation process, to allow for circular reference resolution.
// Also remove any beans that received a temporary reference to the bean.
destroySingleton(beanName);
throw ex;
}
});
bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
}
/**
* 8.2 原型模式的创建
*/
else if (mbd.isPrototype()) {
// It's a prototype -> create a new instance.
Object prototypeInstance = null;
try {
//创建bean前将beanName放入prototypesCurrentlyInCreation中
beforePrototypeCreation(beanName);
prototypeInstance = createBean(beanName, mbd, args);
}
finally {
//创建bean前将beanName从prototypesCurrentlyInCreation中移除
afterPrototypeCreation(beanName);
}
bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}
//指定scope上实例化bean
else {
String scopeName = mbd.getScope();
final Scope scope = this.scopes.get(scopeName);
if (scope == null) {
throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
}
try {
Object scopedInstance = scope.get(beanName, () -> {
beforePrototypeCreation(beanName);
try {
return createBean(beanName, mbd, args);
}
finally {
afterPrototypeCreation(beanName);
}
});
bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
}
catch (IllegalStateException ex) {
throw new BeanCreationException(beanName,
"Scope '" + scopeName + "' is not active for the current thread; consider " +
"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
ex);
}
}
}
catch (BeansException ex) {
cleanupAfterBeanCreationFailure(beanName);
throw ex;
}
}
/**
* 9.检查需要的类型是否符合bean的实际类型
*/
if (requiredType != null && !requiredType.isInstance(bean)) {
try {
T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
if (convertedBean == null) {
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
return convertedBean;
}
catch (TypeMismatchException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Failed to convert bean '" + name + "' to required type '" +
ClassUtils.getQualifiedName(requiredType) + "'", ex);
}
throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
}
}
return (T) bean;
}
分析(重点):
- 提取对应的beanName,因为可能此处是通过别名获取的
- 直接尝试从缓存中获取目标bean的实例, 如果目标bean实例获取失败则尝试从singletonFactories集合中获取创建bean的工厂bean; 因为在创建单例bean的时候会存在依赖注入的情况, 而在创建依赖的时候为了避免循环依赖, spring创建bean的原则是不等bean创建完成就会将创建bean的objectFactory提早曝光, 也就是将ObjectFactory加入到缓存中, 一旦下一个bean创建的时候需要依赖上一个bean则直接使用ObjectFactory
- FactoryBean情况处理; 返回对应的实例,有时候存在诸如FactoryBean的情况并不是直接返回实例本身而是返回指定方法的实例
- 首先进行原型模式的依赖检查,只有在单例情况下才会尝试解决循环依赖,如果原型模式中出现了循环依赖,则抛出异常
- 检查该beanName信息是否存在于工厂中;如果beanDefinitionMap中也就是当前加载的XML配置文件所生成的在类中不包括beanName,则尝试从parentBeanFactory中检测
- 将存储XML配置文件的GerenicBeanDefinition转换为RootBeanDefintion,转换的同时如果父类bean不为空的话,则会合并父类的属性
- 保证当前bean所依赖的bean的初始化(这里并不是循环依赖), 这里主要处理dependsOn属性中配置的目标Bean需要依赖的bean
- 创建bean实例;(单例模式的创建和原型模式的创建)
- 检查需要的类型是否符合bean的实际类型
1. 尝试从缓存中获取
_2. DefaultSingletonBeanRegistry#getSingleton(java.lang.String)
==> DefaultSingletonBeanRegistry#getSingleton(java.lang.String, boolean)实现:
protected Object getSingleton(String beanName, boolean allowEarlyReference) {
/**
* 1.检查缓存中是否存在实例,存在的话就直接返回
*/
Object singletonObject = this.singletonObjects.get(beanName);
/**
* 2.如果缓存中没有,并且当前该实例在正在创建中,则锁定全局变量进行处理
*/
if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
synchronized (this.singletonObjects) {
/**
* 如果此bean正在加载,但是可以从earlySingletonObjects中获取到目标bean,就返回该对象;否则进行创建
*/
singletonObject = this.earlySingletonObjects.get(beanName);
if (singletonObject == null && allowEarlyReference) {
/**
* 当某些方法需要提前初始化的时候会调用addSingletonFactory方法将对应的ObjectFactory初始化策略存储在singletonFactories(缓存中)
* 如果早期目标bean获取失败, 则尝试从缓存中获取创建目标bean的工厂bean(循环依赖解决)
*/
ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
if (singletonFactory != null) {
/**
* 调用预先设定的getObject方法,创建singletonObject
*/
singletonObject = singletonFactory.getObject();
/**
* 记录在earlySingletonObjects缓存中,避免循环依赖
* (不等bean创建完成就将创建bean的ObjectFactory提早曝光加入缓存中,一旦下一个bean创建需要依赖上一个bean,则直接使用ObjectFactory)
*/
this.earlySingletonObjects.put(beanName, singletonObject);
/**
* singletonFactories:用于保存BeanName和创建工厂bean之间的关系,与BeanName相关的bean已经被创建,所以需要从singletonFactories移除BeanName
*/
this.singletonFactories.remove(beanName);
}
}
}
}
return singletonObject;
}
分析(重要):
- 检查缓存中是否存在目标bean的实例, 存在的话就直接返回
- 如果缓存中没有, 并且当前该实例在正在创建中, 则锁定全局变量进行处理
- 如果此bean正在加载, 但是可以从earlySingletonObjects中获取到目标bean, 就返回该对象; 否则进行创建
- 如果早期目标bean实例获取失败, 则尝试从缓存中获取创建目标bean的工厂bean(循环依赖解决)
- 调用预先设定的getObject方法, 创建目标bean实例singletonObject
- 记录在earlySingletonObjects缓存中, 避免循环依赖 (不等bean创建完成就将创建bean的ObjectFactory提早曝光加入缓存中, 一旦下一个bean创建需要依赖上一个bean, 则直接使用ObjectFactory)
2. FactoryBean情况处理
_3. AbstractBeanFactory#getObjectForBeanInstance实现:
protected Object getObjectForBeanInstance(
Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
/**
* 如果指定的name是工厂相关但是beanInstance却不是FactoryBean类型,则验证不通过
* 检查该BeanName是否是FactoryBean的beanName(以&为前缀),
*/
if (BeanFactoryUtils.isFactoryDereference(name)) {
/**
* 如果name是一个普通bean,则直接返回该实例
*/
if (beanInstance instanceof NullBean) {
return beanInstance;
}
/**
* 如果指定的name是工厂相关(以&为前缀),但是beanInstance却不是FactoryBean类型,则验证不通过,抛出异常
*/
if (!(beanInstance instanceof FactoryBean)) {
throw new BeanIsNotAFactoryException(beanName, beanInstance.getClass());
}
}
//如果beanInstance实例不是FactoryBean,或者指定名称是FactoryBean的解引用,也就是普通的bean调用,则直接返回当前的beanInstance实例
if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
//!(beanInstance instanceof FactoryBean) 说明该bean为普通bean对象;
//BeanFactoryUtils.isFactoryDereference(name) 说明期望返回一个beanFactory对象
//用户只需要返回普通的bean对象或者FactoryBean对象
return beanInstance;
}
/**
* 注意:
* 如果我们创建的bean就是我们所需要的bean,那么以上两步就可以满足业务要求
*
* 如果需要使用FactoryBean的getObject()方法获取bean对象的话,需要下面的业务逻辑
*
* 加载FactoryBean(以下为通过beanFactory#getObject返回bean对象)
*/
Object object = null;
if (mbd == null) {
//尝试从缓存中加载bean
object = getCachedObjectForFactoryBean(beanName);
}
if (object == null) {
//到这里已经明确知道beanInstance一定是FactoryBean类型,所以将该bean实例强转为FactoryBean类型, 后面通过该factory的getObject方法获取指定bean实例
FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
//containsBeanDefinition()方法检测beanDefinitionMap中是否已存在定义beanName
if (mbd == null && containsBeanDefinition(beanName)) {
//将存储XML配置文件的GernericBeanDefinition转换为RootBeanDefinition,如果指定BeanName是子Bean的话同时会合并父类的相关属性
mbd = getMergedLocalBeanDefinition(beanName);
}
//是否是用户定义的而不是应用程序本身定义的
boolean synthetic = (mbd != null && mbd.isSynthetic());
/**
* 调用FactoryBeanRegistrySupport类的getObjectFromFactoryBean方法,实现FactoryBean生产Bean对象实例的过程
*/
object = getObjectFromFactoryBean(factory, beanName, !synthetic);
}
return object;
}
分析:
- 如果指定的name是工厂相关但是beanInstance却不是FactoryBean类型,则验证不通过; 检查该BeanName是否是FactoryBean的beanName(以&为前缀) (1)如果name是一个普通bean,则直接返回该实例 (2)如果指定的name是工厂相关(以&为前缀),但是beanInstance却不是FactoryBean类型,则验证不通过,抛出异常
- 如果beanInstance实例不是FactoryBean,或者指定名称是FactoryBean的解引用,也就是普通的bean调用,则直接返回当前的beanInstance实例
- 如果需要使用FactoryBean的getObject()方法获取bean对象的话; 开始尝试通过FactoryBean创建目标bean实例
_3. FactoryBeanRegistrySupport#getObjectFromFactoryBean实现:
protected Object getObjectFromFactoryBean(FactoryBean<?> factory, String beanName, boolean shouldPostProcess) {
// Bean工厂是单态模式,并且Bean工厂缓存中存在指定名称的Bean实例对象
if (factory.isSingleton() && containsSingleton(beanName)) {
synchronized (getSingletonMutex()) {
// 直接从Bean工厂缓存中获取指定名称的Bean实例对象
Object object = this.factoryBeanObjectCache.get(beanName);
// Bean工厂缓存中没有指定名称的实例对象,则生产该实例对象
if (object == null) {
/**
* 调用Bean工厂的getObject方法生产指定Bean的实例对象
*/
object = doGetObjectFromFactoryBean(factory, beanName);
// Only post-process and store if not put there already during getObject() call above
// (e.g. because of circular reference processing triggered by custom getBean calls)
Object alreadyThere = this.factoryBeanObjectCache.get(beanName);
if (alreadyThere != null) {
object = alreadyThere;
}
else {
if (shouldPostProcess) {
if (isSingletonCurrentlyInCreation(beanName)) {
// Temporarily return non-post-processed object, not storing it yet..
return object;
}
beforeSingletonCreation(beanName);
try {
/**
* 为创建出来的Bean实例对象添加BeanPostProcessor后置处理器
*/
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName,
"Post-processing of FactoryBean's singleton object failed", ex);
}
finally {
afterSingletonCreation(beanName);
}
}
if (containsSingleton(beanName)) {
//将生产的实例对象添加到Bean工厂缓存
this.factoryBeanObjectCache.put(beanName, object);
}
}
}
return object;
}
}
//bean工厂不是单例的
else {
Object object = doGetObjectFromFactoryBean(factory, beanName);
if (shouldPostProcess) {
try {
object = postProcessObjectFromFactoryBean(object, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(beanName, "Post-processing of FactoryBean's object failed", ex);
}
}
return object;
}
}
3. 依赖检查
AbstractBeanFactory#isPrototypeCurrentlyInCreation实现:
protected boolean isPrototypeCurrentlyInCreation(String beanName) {
/**
* prototypesCurrentlyInCreation: 存储当前正在创建的bean的名称
*/
Object curVal = this.prototypesCurrentlyInCreation.get();
/**
* 如果正在创建的beanName是原型, 并且已经存在于prototypesCurrentlyInCreation(正在创建的原型类型bean集合)集合中
* 如果是原型,并且已经存在于该集合中, 那么可以判断出此时该bean已经出现循环依赖, 那么对于原型类型, 不解决循环依赖,
* 而是抛出异常
*/
return (curVal != null &&
(curVal.equals(beanName) || (curVal instanceof Set && ((Set<?>) curVal).contains(beanName))));
}
分析: 如果正在创建的bean是单例的, 那么第二次获取该bean时, 是不会执行到这一步的, 会通过前面的缓存获取到早期目标bean实例, 直接返回了; 但是如果陈谷执行到了这里, 那么说明正在创建的bean是原型的, 并且此时是这个原型Bean的第二次获取, 但是第一次获取还没创建完成, 那么可以断定这里出现循环依赖, 需要抛出异常
4. Bean的创建
DefaultSingletonBeanRegistry#getSingleton(java.lang.String, org.springframework.beans.factory.ObjectFactory<?>)实现:
public Object getSingleton(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(beanName, "Bean name must not be null");
//全局变量需要同步
synchronized (this.singletonObjects) {
//首先检查对应的bean是否已经加载过,因为singleton模式其实就是复用已创建的bean,所以这一步是必须的
Object singletonObject = this.singletonObjects.get(beanName);
//如果为空,才进行singleton的bean初始化
if (singletonObject == null) {
if (this.singletonsCurrentlyInDestruction) {
throw new BeanCreationNotAllowedException(beanName,
"Singleton bean creation not allowed while singletons of this factory are in destruction " +
"(Do not request a bean from a BeanFactory in a destroy method implementation!)");
}
if (logger.isDebugEnabled()) {
logger.debug("Creating shared instance of singleton bean '" + beanName + "'");
}
//加载单例前 记录加载状态: 将beanName放入singletonsCurrentlyInCreation属性中,并且从创建检查中排除的bean的名称
beforeSingletonCreation(beanName);
boolean newSingleton = false;
boolean recordSuppressedExceptions = (this.suppressedExceptions == null);
if (recordSuppressedExceptions) {
this.suppressedExceptions = new LinkedHashSet<>();
}
try {
/**
* 初始化bean(通过调用参数传入的ObjectFactory的getObject()方法实例化bean)
* singletonFactory.getObject() ==>
* {@link AbstractAutowireCapableBeanFactory#createBean(String,RootBeanDefinition,Object[])}
*/
singletonObject = singletonFactory.getObject();
newSingleton = true;
}
...
finally {
if (recordSuppressedExceptions) {
this.suppressedExceptions = null;
}
//加载单例后的处理方法调用
afterSingletonCreation(beanName);
}
if (newSingleton) {
//将结果记录至缓存,并删除加载bean过程中所记录的各种状态
addSingleton(beanName, singletonObject);
}
}
return singletonObject;
}
}
分析:
- 首先检查对应的bean是否已经加载过, 因为singleton模式其实就是复用已创建的bean, 所以这一步是必须的
- 加载单例前记录加载状态: 将beanName放入singletonsCurrentlyInCreation属性中, 并且从创建检查中排除的bean的名称
- 初始化bean(通过调用参数传入的ObjectFactory的getObject()方法实例化bean); singletonFactory.getObject() ==>AbstractAutowireCapableBeanFactory#createBean(String,RootBeanDefinition,Object[])
_3. AbstractAutowireCapableBeanFactory#createBean实现:
protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) throws BeanCreationException {
if (logger.isDebugEnabled()) {
logger.debug("Creating instance of bean '" + beanName + "'");
}
RootBeanDefinition mbdToUse = mbd;
//1.锁定class,根据class属性或者根据className来解析Class
Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
mbdToUse = new RootBeanDefinition(mbd);
mbdToUse.setBeanClass(resolvedClass);
}
try {
/**
* 验证及准备覆盖的方法
*/
mbdToUse.prepareMethodOverrides();
}
...
try {
/**
* Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
* 给BeanPostProcessors一个返回代理而不是目标bean实例的机会。
*/
Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
if (bean != null) {
return bean;
}
}
...
try {
/**
* 创建bean
*/
Object beanInstance = doCreateBean(beanName, mbdToUse, args);
if (logger.isDebugEnabled()) {
logger.debug("Finished creating instance of bean '" + beanName + "'");
}
return beanInstance;
}
. . .
}
AbstractAutowireCapableBeanFactory#doCreateBean实现(重点):
protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final @Nullable Object[] args)
throws BeanCreationException {
//实例化bean
BeanWrapper instanceWrapper = null;
/**
* 1.如果是单例,则需要将该bean从未完成的FactoryBean实例的缓存中移除
*/
if (mbd.isSingleton()) {
instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
}
/**
* 2.实例化bean,将BeanDefinition转换为BeanWrapper
*
* 根据指定bean使用对应的策略创建新的实例,如:工厂方法,构造函数自动注入,简单初始化
*/
if (instanceWrapper == null) {
instanceWrapper = createBeanInstance(beanName, mbd, args);
}
//获取已实例化完成的bean(依赖处理和属性注入还未进行)
final Object bean = instanceWrapper.getWrappedInstance();
Class<?> beanType = instanceWrapper.getWrappedClass();
if (beanType != NullBean.class) {
mbd.resolvedTargetType = beanType;
}
/**
* 3.允许后处理器修改合并的bean定义
*/
synchronized (mbd.postProcessingLock) {
if (!mbd.postProcessed) {
try {
//应用MergedBeanDefinitionPostProcessors
applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
}
catch (Throwable ex) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Post-processing of merged bean definition failed", ex);
}
mbd.postProcessed = true;
}
}
/**
* 4.依赖处理 <注意:必须在进行属性注入之前进行循环依赖处理,因为在属性注入时会检测到依赖bean> <---注意!-----
*
* 是否需要提早曝光: 单例 & 允许循环依赖 & 当前bean正在创建中
* isSingletonCurrentlyInCreation(beanName):当该bean开始创建时将该beanName放入singletonsCurrentlyInCreation中,说明该bean正在创建
* 只有正在创建的bean才需要解决循环依赖
*/
boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
isSingletonCurrentlyInCreation(beanName));
if (earlySingletonExposure) {
//日志记录
if (logger.isDebugEnabled()) {
logger.debug("Eagerly caching bean '" + beanName +
"' to allow for resolving potential circular references");
}
/**
* 为避免后期循环依赖,可以在bean初始化完成前将创建实例的ObjectFactory加入工厂
*
* 对bean再一次依赖引用,主要应用于SmartInstantiationAware BeanPostProcessor,
* 其中我们熟知的AOP就是在这里将advice动态织入bean中,若没有则直接返回bean,不做任何处理
*
* addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory)
* {@link ObjectFactory#getObject()} --> {@link AbstractAutowireCapableBeanFactory#getEarlyBeanReference(String, RootBeanDefinition, Object)}
*/
addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
}
/**
* 5.属性填充, 后处理器应用, 初始化方法执行
*/
Object exposedObject = bean;
try {
/**
* 对bean进行填充.将各个属性值注入,其中,可能存在依赖于其他bean的属性,则会递归初始化bean
*/
populateBean(beanName, mbd, instanceWrapper);
/**
* =========> 调用初始化方法,比如init-method(在调用初始化方法之前执行后处理器) <=========== 重点
*/
exposedObject = initializeBean(beanName, exposedObject, mbd);
}
catch (Throwable ex) {
if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
throw (BeanCreationException) ex;
}
else {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
}
}
//检测循环依赖是否已被解决
if (earlySingletonExposure) {
Object earlySingletonReference = getSingleton(beanName, false);
//earlySingletonReference只有在检测到有循环依赖的情况下才不会为空
if (earlySingletonReference != null) {
//如果exposedObject没有在初始化方法中被改变,也就没有被增强
if (exposedObject == bean) {
exposedObject = earlySingletonReference;
}
else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
String[] dependentBeans = getDependentBeans(beanName);
Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
/**
* 6.循环依赖检测
*/
for (String dependentBean : dependentBeans) {
if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
//检测依赖
actualDependentBeans.add(dependentBean);
}
}
/**
* 因为bean创建后其所依赖的bean一定是已经创建的
* actualDependentBeans不为空则表示当前bean创建后其依赖的bean却没有没被全部创建完,也就是说存在循环依赖
*/
if (!actualDependentBeans.isEmpty()) {
...
}
}
}
}
//7.注册DisposableBean
try {
registerDisposableBeanIfNecessary(beanName, bean, mbd);
}
catch (BeanDefinitionValidationException ex) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
}
return exposedObject;
}
分析:
1. 如果是单例, 则需要将该bean从未完成的FactoryBean实例的缓存中移除
2. 实例化bean, 将BeanDefinition转换为BeanWrapper; 根据指定bean使用对应的策略创建新的实例,如:工厂方法,构造函数自动注入,简单初始化
3. 允许后处理器修改合并的bean定义
4. 依赖处理 <注意:必须在进行属性注入之前进行循环依赖处理,因为在属性注入时会检测到依赖bean>
(1)是否需要提早曝光: 单例 & 允许循环依赖 & 当前bean正在创建中
(2)isSingletonCurrentlyInCreation(beanName): 当该bean开始创建时将该beanName放入singletonsCurrentlyInCreation中, 说明该bean正在创建; 只有正在创建的bean才需要解决循环依赖; 为避免后期循环依赖, 可以在bean初始化完成前将创建实例的ObjectFactory加入缓存
5. 属性填充, 后处理器应用, 初始化方法执行
6. 循环依赖检测
4.1 实例化bean
AbstractAutowireCapableBeanFactory#createBeanInstance实现:
protected BeanWrapper createBeanInstance(String beanName, RootBeanDefinition mbd, @Nullable Object[] args) {
//解析class
Class<?> beanClass = resolveBeanClass(mbd, beanName);
if (beanClass != null && !Modifier.isPublic(beanClass.getModifiers()) && !mbd.isNonPublicAccessAllowed()) {
throw new BeanCreationException(mbd.getResourceDescription(), beanName,
"Bean class isn't public, and non-public access not allowed: " + beanClass.getName());
}
Supplier<?> instanceSupplier = mbd.getInstanceSupplier();
if (instanceSupplier != null) {
return obtainFromSupplier(instanceSupplier, beanName);
}
//1.如果工厂方法不为空,则使用工厂方法初始化策略
if (mbd.getFactoryMethodName() != null) {
return instantiateUsingFactoryMethod(beanName, mbd, args);
}
boolean resolved = false;
boolean autowireNecessary = false;
if (args == null) {
synchronized (mbd.constructorArgumentLock) {
//一个类有多个构造函数,每个构造函数都有不同的参数,所以调用前需要先根据参数锁定构造函数或对应的工厂方法
if (mbd.resolvedConstructorOrFactoryMethod != null) {
resolved = true;
autowireNecessary = mbd.constructorArgumentsResolved;
}
}
}
//如果已经解析过,则使用解析好的构造函数方法不需要再次锁定
if (resolved) {
if (autowireNecessary) {
/**
* 构造函数自动注入
*/
return autowireConstructor(beanName, mbd, null, null);
}
else {
/**
* 使用默认构造函数构造
*/
return instantiateBean(beanName, mbd);
}
}
//需要根据参数解析构造函数
Constructor<?>[] ctors = determineConstructorsFromBeanPostProcessors(beanClass, beanName);
if (ctors != null || mbd.getResolvedAutowireMode() == AUTOWIRE_CONSTRUCTOR ||
mbd.hasConstructorArgumentValues() || !ObjectUtils.isEmpty(args)) {
//构造函数自动注入
return autowireConstructor(beanName, mbd, ctors, args);
}
//使用默认构造函数构造
return instantiateBean(beanName, mbd);
}
分析: 该方法中将会根据情况使用不同的策略去实例化目标bean, 相关逻辑比较复杂, 就不在这里分析了, 感兴趣的可以自己分析下
4.2 依赖处理
DefaultSingletonBeanRegistry#addSingletonFactory实现:
protected void addSingletonFactory(String beanName, ObjectFactory<?> singletonFactory) {
Assert.notNull(singletonFactory, "Singleton factory must not be null");
synchronized (this.singletonObjects) {
if (!this.singletonObjects.containsKey(beanName)) {
//此时bean还未创建, 提前将创建bean的BeanFactory暴露到内存中
this.singletonFactories.put(beanName, singletonFactory);
this.earlySingletonObjects.remove(beanName);
this.registeredSingletons.add(beanName);
}
}
}
分析: 在前面解决循环依赖时, 从singletonFactories集合中获取到一个ObjectFactory, 然后通过ObjectFactory的getObject方法获取到了目标bean实例, 由此解决了循环依赖问题; 所以在通过构造方法实例化目标bean之后, 便将目标bean封装到ObjectFactory实例的getObject()方法中, 当getObject()方法被调用时, 便会返回目标bean实例, 在调用getObject方法时实际上执行的是传入的getEarlyBeanReference()方法;
AbstractAutowireCapableBeanFactory#getEarlyBeanReference实现:
protected Object getEarlyBeanReference(String beanName, RootBeanDefinition mbd, Object bean) {
Object exposedObject = bean;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof SmartInstantiationAwareBeanPostProcessor) {
SmartInstantiationAwareBeanPostProcessor ibp = (SmartInstantiationAwareBeanPostProcessor) bp;
exposedObject = ibp.getEarlyBeanReference(exposedObject, beanName);
}
}
}
return exposedObject;
}
分析: 在getEarlyBeanReference()方法中获取目标bean时, 会先去执行容器中已实例化的实现了SmartInstantiationAwareBeanPostProcessor接口的后处理器对目标bean进行处理, 在执行所有合适的处理器后, 返回目标bean
4.3 属性填充
AbstractAutowireCapableBeanFactory#populateBean实现:
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
if (bw == null) {
//获取bean的属性名和值
if (mbd.hasPropertyValues()) {
throw new BeanCreationException(
mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
}
else {
// Skip property population phase for null instance.
//没有可填充的属性,直接返回
return;
}
}
// 应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessAfterInstantiation方法
// 在注入属性前修改bean状态,如果方法中返回false的话,可以终止后面代码运行,直接返回
boolean continueWithPropertyPopulation = true;
if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//返回值为是否继续填充bean
if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
continueWithPropertyPopulation = false;
break;
}
}
}
}
//如果后处理器发出停止填充命令,则终止后续的执行
if (!continueWithPropertyPopulation) {
return;
}
PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME || mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
/**
* 根据名称自动注入
*/
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_NAME) {
autowireByName(beanName, mbd, bw, newPvs);
}
/**
* 根据类型自动注入
*/
if (mbd.getResolvedAutowireMode() == AUTOWIRE_BY_TYPE) {
autowireByType(beanName, mbd, bw, newPvs);
}
pvs = newPvs;
}
//后处理器已经初始化
boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
//需要依赖检查
boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);
if (hasInstAwareBpps || needsDepCheck) {
if (pvs == null) {
pvs = mbd.getPropertyValues();
}
PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
if (hasInstAwareBpps) {
for (BeanPostProcessor bp : getBeanPostProcessors()) {
if (bp instanceof InstantiationAwareBeanPostProcessor) {
InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
//对所有需要依赖检查的属性进行后处理
pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
if (pvs == null) {
return;
}
}
}
}
if (needsDepCheck) {
//依赖检查,对应depends-on属性,3.0已经弃用此属性
checkDependencies(beanName, mbd, filteredPds, pvs);
}
}
if (pvs != null) {
//将属性应用到bean中
applyPropertyValues(beanName, mbd, bw, pvs);
}
}
分析:
- 应用后处理器InstantiationAwareBeanPostProcessor,调用其postProcessAfterInstantiation方法, 在注入属性前修改bean状态,如果方法中返回false的话,可以终止后面代码运行,直接返回
- 根据名称自动注入
- 根据类型自动注入
- 将属性应用到bean中
AbstractAutowireCapableBeanFactory#autowireByName实现:
protected void autowireByName(String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
for (String propertyName : propertyNames) {
if (containsBean(propertyName)) {
//递归初始化相关的bean
Object bean = getBean(propertyName);
pvs.add(propertyName, bean);
//注册依赖bean
registerDependentBean(propertyName, beanName);
//日志记录
if (logger.isDebugEnabled()) {
logger.debug("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");
}
}
}
}
分析: 获取所有的属性名称, 如果属性名称是存在于容器中的, 那么需要进行实例化, 将属性名称以及属性实例维护在MutablePropertyValues实例中, 后面会将属性应用到目标bean中
AbstractAutowireCapableBeanFactory#autowireByType实现:
protected void autowireByType(
String beanName, AbstractBeanDefinition mbd, BeanWrapper bw, MutablePropertyValues pvs) {
TypeConverter converter = getCustomTypeConverter();
if (converter == null) {
converter = bw;
}
Set<String> autowiredBeanNames = new LinkedHashSet<>(4);
//寻找bw中需要依赖注入的属性名称(找到Bean中属性是对象类型的属性)
String[] propertyNames = unsatisfiedNonSimpleProperties(mbd, bw);
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()) {
//探测到指定属性的set方法
MethodParameter methodParam = BeanUtils.getWriteMethodParameter(pd);
// Do not allow eager init for type matching in case of a prioritized post-processor.
boolean eager = !PriorityOrdered.class.isInstance(bw.getWrappedInstance());
DependencyDescriptor desc = new AutowireByTypeDependencyDescriptor(methodParam, eager);
//解析指定beanName的属性所匹配的值,并把解析到的属性名称存储在autoWiredBeanName中,当属性存在多个封装bean时,如:
//@Autowired
//private List<A> aList;将会找到所有匹配A类型的bean并将其注入;autowiredArgument的类型可能是集合,数组,对象等
Object autowiredArgument = resolveDependency(desc, beanName, autowiredBeanNames, converter);
//将属性名和属性值添加到MutablePropertyValues中
if (autowiredArgument != null) {
pvs.add(propertyName, autowiredArgument);
}
for (String autowiredBeanName : autowiredBeanNames) {
//注册依赖
registerDependentBean(autowiredBeanName, beanName);
if (logger.isDebugEnabled()) {
logger.debug("Autowiring by type from bean name '" + beanName + "' via property '" +
propertyName + "' to bean named '" + autowiredBeanName + "'");
}
}
autowiredBeanNames.clear();
}
}
catch (BeansException ex) {
throw new UnsatisfiedDependencyException(mbd.getResourceDescription(), beanName, propertyName, ex);
}
}
}
4.4 执行初始化方法
AbstractAutowireCapableBeanFactory#initializeBean实现:
protected Object initializeBean(final String beanName, final Object bean, @Nullable RootBeanDefinition mbd) {
if (System.getSecurityManager() != null) {
AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
invokeAwareMethods(beanName, bean);
return null;
}, getAccessControlContext());
}
else {
/**
* 对特殊的bean处理:Aware,BeanClassLoaderAware,BeanFactoryAware
*/
invokeAwareMethods(beanName, bean);
}
Object wrappedBean = bean;
if (mbd == null || !mbd.isSynthetic()) {
/**
* 应用后处理器(在bean初始化之前调用)
*/
wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
}
try {
/**
* **用户自定义的init方法, 完成初始化
*/
invokeInitMethods(beanName, wrappedBean, mbd);
}
catch (Throwable ex) {
throw new BeanCreationException(
(mbd != null ? mbd.getResourceDescription() : null),
beanName, "Invocation of init method failed", ex);
}
if (mbd == null || !mbd.isSynthetic()) {
/**
* 后处理器应用(在bean初始化之后调用)
*/
wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
}
return wrappedBean;
}
分析:
- 应用后处理器(在bean初始化之前调用)
- **用户自定义的init方法, 完成初始化
- 后处理器应用(在bean初始化之后调用)
AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsBeforeInitialization实现:
@Override
public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//获取所有已注册的BeanPostProcessor,遍历执行每一个BeanPostProcessor中重写的postProcessBeforeInitialization方法
for (BeanPostProcessor processor : getBeanPostProcessors()) {
Object current = processor.postProcessBeforeInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
AbstractAutowireCapableBeanFactory#applyBeanPostProcessorsAfterInitialization实现:
@Override
public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName)
throws BeansException {
Object result = existingBean;
//获取所有已注册的BeanPostProcessor,遍历执行每一个BeanPostProcessor中重写的postProcessAfterInitialization方法
for (BeanPostProcessor processor : getBeanPostProcessors()) {
/**
* AOP应用:
* {@link org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator#postProcessAfterInitialization(java.lang.Object, java.lang.String)}
*/
Object current = processor.postProcessAfterInitialization(result, beanName);
if (current == null) {
return result;
}
result = current;
}
return result;
}
分析: 这里会在初始化方法执行前后分别执行容器中所有后处理器的postProcessBeforeInitialization和postProcessAfterInitialization方法, 尝试对目标进行扩展; AOP就是在这里实现的, 关于Aop的相关逻辑分析可以看这篇博客: Spring源码解析(AOP深度解析)
AbstractAutowireCapableBeanFactory#invokeInitMethods实现:
protected void invokeInitMethods(String beanName, final Object bean, @Nullable RootBeanDefinition mbd)
throws Throwable {
//首先检查是否是InitializingBean,如果是的话需要调用afterPropertiesSet方法
boolean isInitializingBean = (bean instanceof InitializingBean);
if (isInitializingBean && (mbd == null || !mbd.isExternallyManagedInitMethod("afterPropertiesSet"))) {
if (logger.isDebugEnabled()) {
logger.debug("Invoking afterPropertiesSet() on bean with name '" + beanName + "'");
}
if (System.getSecurityManager() != null) {
try {
AccessController.doPrivileged((PrivilegedExceptionAction<Object>) () -> {
((InitializingBean) bean).afterPropertiesSet();
return null;
}, getAccessControlContext());
}
catch (PrivilegedActionException pae) {
throw pae.getException();
}
}
else {
//属性初始化后的梳理
((InitializingBean) bean).afterPropertiesSet();
}
}
if (mbd != null && bean.getClass() != NullBean.class) {
String initMethodName = mbd.getInitMethodName();
if (StringUtils.hasLength(initMethodName) &&
!(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
!mbd.isExternallyManagedInitMethod(initMethodName)) {
//调用自定义初始化方法
invokeCustomInitMethod(beanName, bean, mbd);
}
}
}
分析: 如果目标bean实现了InitializingBean接口并重写afterPropertiesSet()方法, 那么这里会触发该方法; 在afterPropertiesSet()方法执行之后会执行自定义初始化方法; (afterPropertiesSet方法将会在属性注入之后, 初始化方法执行之前触发)
至此, bean的初始化流程解析完成, 这篇博客主要围绕初始化流程解析, 没有过多去解析一些细节问题, 感兴趣的同学可以自己分析一下;
相关文章:
Spring源码解析二 (IOC容器初始化方式一:XmlBeanFactory)
Spring源码解析三 (IOC容器初始化方式二:ClassPathXmlApplicationContext)
Spring源码解析四 (IOC容器初始化方式三: AnnotationConfigApplicationContext[包路径配置方式])
Spring源码解析五 (IOC容器初始化方式四: AnnotationConfigApplicationContext[Java配置类方式])
推荐阅读
-
Spring中Bean的生命周期使用解析
-
spring5 源码深度解析----- 被面试官给虐懵了,竟然是因为我不懂@Configuration配置类及@Bean的原理
-
基于Spring注解的上下文初始化过程源码解析(一)
-
SpringBoot 源码解析 (七)----- Spring Boot的核心能力 - SpringBoot如何实现SpringMvc的?
-
SpringBoot 源码解析 (六)----- Spring Boot的核心能力 - 内置Servlet容器源码分析(Tomcat)
-
通过实例解析spring bean之间的关系
-
spring源码分析系列5:ApplicationContext的初始化与Bean生命周期
-
spring源码分析6: ApplicationContext的初始化与BeanDefinition的搜集入库
-
Mybaits 源码解析 (十二)----- Mybatis的事务如何被Spring管理?Mybatis和Spring事务中用的Connection是同一个吗?
-
Spring 的 Bean 生命周期,11 张高清流程图及代码,深度解析