spring加载流程refresh之finishBeanFactoryInitialization(beanFactory)

实例化所有Bean

  • AbstractApplicationContext.finishBeanFactoryInitialization()
    • 判断是否有bdName为conversionService的bd(实现ConversionService接口)
    • 判断是否有LoadTimeWeaverAware类型的bd
  • DefaultListableBeanFactory.preInstantiateSingletons()预处理
    • 跳过抽象、原型、懒加载的bd
    • 判断是否是FactoryBean
  • AbstractApplicationContext.getBean(bdName)
    • 处理bdName去掉`&`
    • 判断bd是否有@DependsOn
    • 判断bd的作用域分别进行实例化
  • AbstractAutowireCapableBeanFactory.createBean
    • 通过BeanPostProcessor实例化bd
    • doCreateBean
      • 判断是否有缓存,没有则创建bean实例
        • 确定构造函数然后实例化
      • MergedBeanDefinitionPostProcessor后处理器修改已合并的bean定义
      • 解决bean之间的循环依赖
      • 填充bean属性populateBean
      • bean的初始化initializeBean

注释: 到了spring加载流程最复杂的一步,开始实例化所有的bd

AbstractApplicationContext.finishBeanFactoryInitialization()

// 实例化所有的bd
this.finishBeanFactoryInitialization(beanFactory);
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // 判断是否有bdName为conversionService的bd(实现ConversionService接口),有的话注册为格式转换器服务类
    if (beanFactory.containsBean("conversionService") && beanFactory.isTypeMatch("conversionService", ConversionService.class)) {
        beanFactory.setConversionService((ConversionService)beanFactory.getBean("conversionService", ConversionService.class));
    }

    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver((strVal) -> {
            return this.getEnvironment().resolvePlaceholders(strVal);
        });
    }
    // 获取LoadTimeWeaverAware类型的bd,提前实例化
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    String[] var3 = weaverAwareNames;
    int var4 = weaverAwareNames.length;
    for(int var5 = 0; var5 < var4; ++var5) {
        String weaverAwareName = var3[var5];
        this.getBean(weaverAwareName);
    }

    beanFactory.setTempClassLoader((ClassLoader)null);
    // 冻结上下文,不允许再进行修改配置
    beanFactory.freezeConfiguration();
    // 实例化预处理
    beanFactory.preInstantiateSingletons();
}

判断是否有bdName为conversionService的bd(实现ConversionService接口)

这里是结合spring MVC使用的,类似页面传递String类型的时间格式到后台可以格式化为Date类型
容器初始化完成后,默认是没有格式转换器的
spring加载流程refresh之finishBeanFactoryInitialization(beanFactory)_第1张图片
spring内部有个DefaultConversionService,但是没有注册进容器,所以spring找不到。
可以通过配置注入容器,然后spring在这一步就会找到DefaultConversionService并注册到conversionService
DefaultConversionService会注册很多spring自带的格式转换器,包括时间,集合等

@Bean
public ConversionService conversionService(){
    DefaultConversionService ConversionService = new DefaultConversionService();
    return ConversionService;
}

在这里插入图片描述

判断是否有LoadTimeWeaverAware类型的bd

这里会提前实例化LoadTimeWeaverAware类型的bd,this.getBean(bdName)方法会进行实例化bd,后面具体分析

DefaultListableBeanFactory.preInstantiateSingletons()预处理

this.beanDefinitionNames就是之前注册bd的时候添加的bdName集合

List beanNames = new ArrayList(this.beanDefinitionNames);
Iterator var2 = beanNames.iterator();

跳过抽象、原型、懒加载的bd

懒加载与原型的bd,不实例化进ioc容器,在调用的时候才会去实例化

String beanName;
RootBeanDefinition bd;
do {
    do {
        do {
              .
              .
              .
            beanName = (String)var2.next();
            // 获取bd
            bd = this.getMergedLocalBeanDefinition(beanName);
        } while(bd.isAbstract());// 如果是抽象的则继续循环
    } while(!bd.isSingleton());// 如果不是单例则继续循环
} while(bd.isLazyInit());// 如果是懒加载的则继续循环

判断是否是FactoryBean

if (this.isFactoryBean(beanName)) {
    // 如果是FactoryBean
    FactoryBean factory = (FactoryBean)this.getBean("&" + beanName);
    boolean isEagerInit;
    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
        isEagerInit = ((Boolean)AccessController.doPrivileged(() -> {
            return ((SmartFactoryBean)factory).isEagerInit();
        }, this.getAccessControlContext())).booleanValue();
    } else {
        isEagerInit = factory instanceof SmartFactoryBean && ((SmartFactoryBean)factory).isEagerInit();
    }

    if (isEagerInit) {
        this.getBean(beanName);
    }
} else {
    this.getBean(beanName);
}

实现FactoryBean接口的bd是spring中一种特殊的bean,获取该bd其实是getObject()返回的内容,但是可以通过"&" + beanName获取到该bd本身。

AbstractApplicationContext.getBean(bdName)

public Object getBean(String name) throws BeansException {
    return this.doGetBean(name, (Class)null, (Object[])null, false);
}

跳到doGetBean

处理bdName去掉&

这里有可能传进来的是个FactoryBean,所以需要处理下bdName

String beanName = this.transformedBeanName(name);

做个记录,标识bd正在实例化

if (!typeCheckOnly) {
   this.markBeanAsCreated(beanName);
}

判断bd是否有@DependsOn

@DependsOn控制bean的加载顺序

// 根据bdName获取bd
RootBeanDefinition mbd = this.getMergedLocalBeanDefinition(beanName);
this.checkMergedBeanDefinition(mbd, beanName, args);
// 判断是否存在@DependsOn
String[] dependsOn = mbd.getDependsOn();
String[] var11;
if (dependsOn != null) {
    var11 = dependsOn;
    int var12 = dependsOn.length;
    for(int var13 = 0; var13 < var12; ++var13) {
        String dep = var11[var13];
        if (this.isDependent(beanName, dep)) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
        }

        this.registerDependentBean(dep, beanName);
        // 先实例化@DependsOn中的bd
        this.getBean(dep);
    }
}

判断bd的作用域分别进行实例化

有人说前面不是判断跳过了原型的bd吗,这里为什么还要判断是单例还是原型?因为前面是获取容器中所有的bd进行实例化做的判断,如果单单只是调用某一个bdgetBean(bdName)的话,比如

EmailService service = context.getBean("emailService ");

也是需要先判断一下作用域,然后进行实例化

if (mbd.isSingleton()) {
    sharedInstance = this.getSingleton(beanName, () -> {
        try {
            return this.createBean(beanName, mbd, args);
        } catch (BeansException var5) {
            this.destroySingleton(beanName);
            throw var5;
        }
    });
    bean = this.getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
} else if (mbd.isPrototype()) {
    var11 = null;

    Object prototypeInstance;
    try {
        this.beforePrototypeCreation(beanName);
        prototypeInstance = this.createBean(beanName, mbd, args);
    } finally {
        this.afterPrototypeCreation(beanName);
    }

    bean = this.getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
}

AbstractAutowireCapableBeanFactory.createBean

实现自动注入功能的工厂

通过BeanPostProcessor实例化bd

这里可以通过BeanPostProcessor实例化bd,不需要进行后面的流程,记住有这么个东西,一般没用。。。

beanInstance = this.resolveBeforeInstantiation(beanName, mbdToUse);
if (beanInstance != null) {
    return beanInstance;
}
protected Object resolveBeforeInstantiation(String beanName, RootBeanDefinition mbd) {
    Object bean = null;
    if (!Boolean.FALSE.equals(mbd.beforeInstantiationResolved)) {
        if (!mbd.isSynthetic() && this.hasInstantiationAwareBeanPostProcessors()) {
            Class targetType = this.determineTargetType(beanName, mbd);
            if (targetType != null) {
                bean = this.applyBeanPostProcessorsBeforeInstantiation(targetType, beanName);
                if (bean != null) {
                    bean = this.applyBeanPostProcessorsAfterInitialization(bean, beanName);
                }
            }
        }

        mbd.beforeInstantiationResolved = bean != null;
    }

    return bean;
}

doCreateBean

判断是否有缓存,没有则创建bean实例

BeanWrapper instanceWrapper = null;
if (mbd.isSingleton()) {
    // 注意factoryBeanInstanceCache是ConcurrentMap,remove方法会返回删除的键值(如果不存在返回null)
    instanceWrapper = (BeanWrapper)this.factoryBeanInstanceCache.remove(beanName);
}
if (instanceWrapper == null) {
    // 如果factoryBeanInstanceCache没有缓存对应的BeanWrapper,则重新创建bean实例
    instanceWrapper = this.createBeanInstance(beanName, mbd, args);
}

确定构造函数然后实例化

createBeanInstance方法内部

// 确定bd的构造函数
Constructor[] ctors = this.determineConstructorsFromBeanPostProcessors(beanClass, beanName);
return ctors == null && mbd.getResolvedAutowireMode() != 3 && !mbd.hasConstructorArgumentValues() && ObjectUtils.isEmpty(args) ? this.instantiateBean(beanName, mbd) : this.autowireConstructor(beanName, mbd, ctors, args);

如果为空(没有带参构造函数),则this.instantiateBean(beanName, mbd),否则this.autowireConstructor(beanName, mbd, ctors, args);,这里先不具体分析怎么实例化bd

MergedBeanDefinitionPostProcessor后处理器修改已合并的bean定义

synchronized(mbd.postProcessingLock) {
    if (!mbd.postProcessed) {
        try {
            this.applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
        } catch (Throwable var17) {
            throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Post-processing of merged bean definition failed", var17);
        }

        mbd.postProcessed = true;
    }
}

解决bean之间的循环依赖

将正在创建的bean放入singletonFactories,这里是个面试点,会单独出一篇文章详解

// 提前缓存ObjectFactory以解决bean之间的循环依赖
// mbd.isSingleton()->是否单例
// allowCircularReferences->是否允许循环依赖
// isSingletonCurrentlyInCreation->该bean是否创建中
boolean earlySingletonExposure = mbd.isSingleton() && this.allowCircularReferences && this.isSingletonCurrentlyInCreation(beanName);
if (earlySingletonExposure) {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
    }

    this.addSingletonFactory(beanName, () -> {
        return this.getEarlyBeanReference(beanName, mbd, bean);
    });
}

填充bean属性populateBean

会单独出一篇文章详解

this.populateBean(beanName, mbd, instanceWrapper);

bean的初始化initializeBean

会单独出一篇文章详解

 exposedObject = this.initializeBean(beanName, exposedObject, mbd);
protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(() -> {
            this.invokeAwareMethods(beanName, bean);
            return null;
        }, this.getAccessControlContext());
    } else {
        // 完成几个特殊*Aware接口的setter方法的注入
        this.invokeAwareMethods(beanName, bean);
    }

    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        // 执行bpp初始化之前执行的方法
        wrappedBean = this.applyBeanPostProcessorsBeforeInitialization(bean, beanName);
    }

    try {
        // 执行初始化方法(如果该bean实现了InitializingBean方法)
        this.invokeInitMethods(beanName, wrappedBean, mbd);
    } catch (Throwable var6) {
        throw new BeanCreationException(mbd != null ? mbd.getResourceDescription() : null, beanName, "Invocation of init method failed", var6);
    }

    if (mbd == null || !mbd.isSynthetic()) {
        // 执行bpp初始化之后执行的方法(aop增强就是在这里完成的)
        wrappedBean = this.applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }

    return wrappedBean;
}

你可能感兴趣的:(spring源码)