Bean life cycle--the creation process of Bean

Other URL

See the creation process of Bean through the source code

Introduction

Description

        The core modules of Spring are IOC and AOP, and creating Bean in IOC is a very important part. During the startup of Spring, finishBeanFactoryInitialization() is called in the refresh() method. The creation of a non-lazy singleton bean is completed in finishBeanFactoryInitialization. So to figure out the bean creation process, we must start with the source code of the finishBeanFactoryInitialization() method.

Overall process

AbstractApplicationContext#refresh()
    finishBeanFactoryInitialization(beanFactory); //AbstractApplicationContext abstract class
        beanFactory.preInstantiateSingletons(); //DefaultListableBeanFactory class. (Implemented ConfigurableListableBeanFactory interface)
            preInstantiateSingletons() //DefaultListableBeanFactory class. (Implemented ConfigurableListableBeanFactory interface)
                getBean(beanName) //AbstractBeanFactory abstract class (implemented BeanFactory interface)
                    doGetBean(name, null, null, false) //AbstractBeanFactory abstract class. Own method
                        createBean(beanName, mbd, args) //AbstractAutowireCapableBeanFactory abstract class (implemented AbstractBeanFactory)
                            doCreateBean(beanName, mbdToUse, args)//AbstractAutowireCapableBeanFactory abstract class. Own method
                                createBeanInstance(beanName, mbd, args); //Create instance
                                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName) //post-processors modify bean definition
                                addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); // Resolve the circular dependency
                                populateBean(beanName, mbd, instanceWrapper); //fill the properties
                                initializeBean(beanName, exposedObject, mbd); //initialize the bean

finishBeanFactoryInitialization

Located in: AbstractApplicationContext abstract class.

Overview

        This method is very important. It completes the instantiation and initialization of all non-lazy loaded singleton Beans , the filling of attributes, and the resolution of circular dependencies .

        The instantiation and initialization process of the object are deliberately separated here, because in the process of creating the Bean in Spring, the Bean first creates the object through reflection, and then assigns the properties of the object through the post processor (BeanPostProcessor). So the instantiation here refers to the creation of the Bean, and the initialization refers to the assignment of the bean's properties.

Source code

The code of finishBeanFactoryInitialization() method is as follows. The creation and initialization of the bean are implemented in beanFactory.preInstantiateSingletons().

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // 初始化转换服务
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
            beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
        beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    }
    // 如果前面没有注册一个类似于PropertyPlaceholderConfigurer后置处理器的bean,那么在这儿会注册一个内置的属性后置处理器
    // 这儿主要是处理被加了注解的属性
    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }
    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }
    beanFactory.setTempClassLoader(null);
    // 将BeanFactory的configurationFrozen属性设置为true,给frozenBeanDefinitionNames属性赋值
    // 目的是为了不让在其他的地方在修改bean的BeanDefinition
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    // 实例化剩下所有的非懒加载的单例
    beanFactory.preInstantiateSingletons();
}

preInstantiateSingletons

Located in: DefaultListableBeanFactory class. (Implemented ConfigurableListableBeanFactory interface)

Overview

        This method will first determine whether the bean is a FactoryBean, and whether to instantiate the object returned by FactoryBean's getObject() immediately, but in the end, it calls the getBean() method to instantiate the object. After the Bean is instantiated and initialized, it will be judged whether the Bean has implemented the SmartSingletonInitializing interface, and if it has been implemented, the afterSingletonInstantiated() method of the interface will be called.

        Tips: FactoryBean is mentioned here, not BeanFactory. The two names are very similar, but their functions are very different. Later, I will write a separate article to introduce FactoryBean, and analyze the principle of Spring and MyBatis integration through FactoryBean.

        FactoryBean is an interface. The implementation class of the interface will register two beans in the container, one is the object of the type represented by the implementation class itself, and the other is the bean returned by overriding the getObject() method in the FactoryBean interface. In the following example: Two beans will be registered in the container, one is MapperFactoryBean itself, and the other is UserMapper.

@Component
public class MapperFactoryBean implements FactoryBean {
    @Override
    public Object getObject() throws Exception {
        return new UserMapper();
    }

    @Override
    public Class<?> getObjectType() {
        return UserMapper.class;
    }
}

Because the bean instantiation process is too complicated, the source code will be analyzed in conjunction with the flowchart later. The execution flow chart of the preInstantiatedSingletons() method is as follows

Whether it is a FactoryBean or an ordinary Bean, the getBean() method is ultimately called to create the bean.

Source code

public void preInstantiateSingletons() throws BeansException {
    if (logger.isDebugEnabled()) {
        logger.debug("Pre-instantiating singletons in " + this);
    }
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            // 判断是否是factoryBean,如果是FactoryBean,则进行FactoryBean原生的实例化(非getObject()方法对应的对象)。
            // 还需要判断它是否立即实例化getObject()返回的对象,根据SmartFactoryBean的isEagerInit()的返回值判断是否需要立即实例化
            if (isFactoryBean(beanName)) {
                // 首先实例化BeanFactory的原生对象,然后再根据isEagerInit()判断是否实例化BeanFactory中getObject()返回的类型的对象
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                    final FactoryBean<?> factory = (FactoryBean<?>) bean;
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                        ((SmartFactoryBean<?>) factory)::isEagerInit,
                                getAccessControlContext());
                    } else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    // 如果isEagerInit为true,则立即实例化FactoryBean所返回的类型的对象
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            } else {
                getBean(beanName);
            }
        }
    }
    // 在bean实例化以及属性赋值完成后,如果bean实现了SmartInitializingSingleton接口,则回调该接口的方法
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {
            final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
            if (System.getSecurityManager() != null) {
                AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                    smartSingleton.afterSingletonsInstantiated();
                    return null;
                }, getAccessControlContext());
            } else {
                smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}

getBean ()

Located in: AbstractBeanFactory abstract class (implemented BeanFactory interface)

Overview

Call doGetBean(name, null, null, false) //AbstractBeanFactory abstract class. Own method

Source code

public Object getBean(String name) throws BeansException {
	return doGetBean(name, null, null, false);
}

doGetBean

Located at: AbstractBeanFactory abstract class. Own method

Overview

  1. In the doGetBean() method, it will be obtained from the cache first (that is, from the singletonObjects map of the DefaultSingletonBeanRegistry (the name of the bean is the key, and the bean object is the value). Why should it be obtained from the cache first? Because it is from the Spring container Obtaining an object and creating an object are through the getBean() method. For a singleton object, the object is created only once, if it exists, it does not need to be created). If it exists in the cache, call the getObjectForBeanInstance() method, and then return the bean. If it does not exist in the cache, continue to execute.
  2. Then get the BeanDefinition object corresponding to the Bean. Then determine whether the bean is dependent, String[] dependsOn = mbd.getDependsOn(), if there are dependent objects, then the dependent objects will be instantiated first.
  3. After the dependent object is created, the getSingleton(beanName, lambda) method will be called. The second parameter of this method is a lambda expression. The logic to create the bean is in the body of the expression, that is, the createBean() method. The createBean() method will create the completed bean, and then in the getSingleton(beanName, lambda) method, the created bean will be stored in the singletonObjects property. CreateBean() will be analyzed later.
  4. After the bean is created in the previous step, getObjectForBeanInstance() will eventually be called. The logic of this method is relatively simple. First judge whether the bean is a FactoryBean, if not, then return the bean directly; if it is, then judge whether the beanName starts with an ampersand, if it is, it means that the original object of the FactoryBean is obtained, then directly Return the bean; if it does not start with the & symbol, it will return the return value object of the FactoryBean's getObject() method.

Source code

The doGetBean() method code is as follows

protected <T> T doGetBean(final String name, @Nullable final Class<T> requiredType,
        @Nullable final Object[] args, boolean typeCheckOnly) throws BeansException {
    final String beanName = transformedBeanName(name);
    Object bean;
    // Eagerly check singleton cache for manually registered singletons.
    Object sharedInstance = getSingleton(beanName);
    if (sharedInstance != null && args == null) {
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }
    else {
        // Fail if we're already creating this bean instance:
        // We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
        // Check if bean definition exists in this factory.
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (parentBeanFactory instanceof AbstractBeanFactory) {
                return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                        nameToLookup, requiredType, args, typeCheckOnly);
            }
            else if (args != null) {
                // Delegation to parent with explicit args.
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else {
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }
        if (!typeCheckOnly) {
            // 标记bean为已创建
            // 并清除beanDefinition的缓存(mergedBeanDefinitions)
            markBeanAsCreated(beanName);
        }
        try {
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            // 检查bean是否是抽象类
            checkMergedBeanDefinition(mbd, beanName, args);
            // Guarantee initialization of beans that the current bean depends on.
            // 保证当前bean所依赖的bean初始化
            String[] dependsOn = mbd.getDependsOn();
            if (dependsOn != null) {
                for (String dep : dependsOn) {
                    // isDependent()方法用来判断dep是否依赖beanName
                    if (isDependent(beanName, dep)) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                    }
                    // 保存下依赖关系
                    registerDependentBean(dep, beanName);
                    try {
                        getBean(dep);
                    }
                    catch (NoSuchBeanDefinitionException ex) {
                        throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                    }
                }
            }
            // Create bean instance.
            if (mbd.isSingleton()) {
                // 此时在getSingleton方法中传入了一个lambda表达式,
                // 此时不会立即执行lambda表达式,而是在调用这个lambda表达式的getObject()方法时才开始执行lambda的方法体
                sharedInstance = getSingleton(beanName, () -> {
                    try {
                        return createBean(beanName, mbd, args);
                    }
                    catch (BeansException ex) {
                        destroySingleton(beanName);
                        throw ex;
                    }
                });
                bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
            }

            else if (mbd.isPrototype()) {
                // It's a prototype -> create a new instance.
                Object prototypeInstance = null;
                try {
                    beforePrototypeCreation(beanName);
                    prototypeInstance = createBean(beanName, mbd, args);
                }
                finally {
                    afterPrototypeCreation(beanName);
                }
                bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
            }
            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;
        }
    }
    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) {
            throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
        }
    }
    return (T) bean;
}

The function of the getObjectForBeanInstance() method is to determine whether to return the FactoryBean native object or the object returned by the getObject() method according to the beanName. If the beanName starts with an ampersand, it means that the FactoryBean native object is returned, otherwise it returns the return from the getObject() method. Object.

protected Object getObjectForBeanInstance(
        Object beanInstance, String name, String beanName, @Nullable RootBeanDefinition mbd) {
    if (BeanFactoryUtils.isFactoryDereference(name)) {
        if (beanInstance instanceof NullBean) {
            return beanInstance;
        }
        if (!(beanInstance instanceof FactoryBean)) {
            throw new BeanIsNotAFactoryException(transformedBeanName(name), beanInstance.getClass());
        }
    }

    // 如果不是一个FactoryBean对象或者是获取FactoryBean的原生对象(原生对象指的是beanName是以&开头)
    // 此时可以直接返回bean
    if (!(beanInstance instanceof FactoryBean) || BeanFactoryUtils.isFactoryDereference(name)) {
        return beanInstance;
    }

    // 如果是获取FactoryBean的getObject()方法返回的类型对象,则需要进入到如下逻辑
    // 对于getObject()方法,它返回的对象是在在第一次调用getObject方法时进行实例化的,实例化完成以后,会将结果缓存在factoryBeanObjectCache中
    Object object = null;
    if (mbd == null) {
        object = getCachedObjectForFactoryBean(beanName);
    }
    if (object == null) {
        // Return bean instance from factory.
        FactoryBean<?> factory = (FactoryBean<?>) beanInstance;
        // Caches object obtained from FactoryBean if it is a singleton.
        if (mbd == null && containsBeanDefinition(beanName)) {
            mbd = getMergedLocalBeanDefinition(beanName);
        }
        boolean synthetic = (mbd != null && mbd.isSynthetic());
        // 获取FactoryBean返回的对象
        object = getObjectFromFactoryBean(factory, beanName, !synthetic);
    }
    return object;
}

createBean

Located at: AbstractAutowireCapableBeanFactory abstract class (implemented AbstractBeanFactory)

Overview

doGetBean() will eventually call createBean() to create the bean.

In the code of the createBean() method, there are mainly two lines of core code:

Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
Object beanInstance = doCreateBean(beanName, mbdToUse, args);

Flow chart of createBean() method

resolveBeforeInstantiation()

  1. This method is called before the bean is instantiated
  2. In this method, the post processor (BeanPostProcessor) is executed for the first time .
    1. The implementation here is: the postProcessBeforeInstantiation() method of InstantiationAwareBeanPostProcessor, which processes the bean before instantiation.
    2. The significance of this extension point is significant. Example: Spring's AOP is implemented here, the corresponding class: AnnotationAwareAspectJAutoProxyCreator. See: Spring principle--AOP_feiying0canglang's blog -CSDN blog
  3. If the return value of resolveBeforeInstantiation() is not null, the result will be returned directly. If it is null, the method doCreateBean() will continue to execute. In the doCreateBean() method, operations such as Bean instantiation, attribute assignment, and initialization are performed.

Source code of createBean() method

protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
        throws BeanCreationException {
    RootBeanDefinition mbdToUse = mbd;
    // Make sure bean class is actually resolved at this point, and
    // clone the bean definition in case of a dynamically resolved Class
    // which cannot be stored in the shared merged bean definition.
    Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
    if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
        mbdToUse = new RootBeanDefinition(mbd);
        mbdToUse.setBeanClass(resolvedClass);
    }
    // Prepare method overrides.
    try {
        mbdToUse.prepareMethodOverrides();
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
                beanName, "Validation of method overrides failed", ex);
    }
    try {
        // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
        // 第一次调用后置处理器(执行所有InstantiationAwareBeanPostProcessor的子类)
        // 如果InstantiationAwareBeanPostProcessor的子类的postProcessBeforeInstantiation()方法返回值不为空,表示bean需要被增强,
        // 此时将不会执行后面的逻辑,AOP的实际应用就是在这儿实现的
        Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
        if (bean != null) {
            return bean;
        }
    }
    catch (Throwable ex) {
        throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
                "BeanPostProcessor before instantiation of bean failed", ex);
    }

    try {
        // 第二次执行后置处理器的入口
        Object beanInstance = doCreateBean(beanName, mbdToUse, args);
        if (logger.isDebugEnabled()) {
            logger.debug("Finished creating instance of bean '" + beanName + "'");
        }
        return beanInstance;
    }
    catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
        throw ex;
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
                mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
    }
}

doCreateBean

Located at: AbstractAutowireCapableBeanFactory abstract class. Own method.

flow chart

description

  1. createBeanInstance(beanName, mbd, args); //Create an instance. Bean creation through reflection.
    1. Execute the second post processor (BeanPostProcessor): SmartInstantiationAwareBeanPostProcessor#determineCandidateConstructors(), function: infer which constructor the Bean should use to instantiate the object. Typical classes:
      1. AutowiredAnnotationBeanPostProcessor。
  2. applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName) //post-processors modify bean definition
    1. Find MergedBeanDefinitionPostProcessor from all post processors and call its postProcessMergedBeanDefinition()
      1. Execute the third post processor (BeanPostProcessor): cache the annotation metadata information of the bean, and use it when filling in the attributes later. Here, the attributes annotated with @Autowired, @Resource, etc. will be parsed and cached. Typical classes:
        1. CommonAnnotationBeanPostProcessor: Process annotations in JSR-250, such as @Resource, @PostConstruct, @PreDestroy.
        2. AutowiredAnnotationBeanPostProcessor:@Autowired,@Value,@Inject
        3. RequiredAnnotationBeanPostProcessor
  3. addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean)); //Resolve circular references
    1. Purpose: Expose the bean in advance to solve the problem of circular references. The second parameter of the method is the lambda expression, which will execute the post processor again.
    2. Detailed explanation: Put the semi-finished bean (the attribute of the bean has not yet been assigned, and the automatic assembly has not been completed) into the attribute of the singletonFactories of the DefaultSingletonBeanRegistry class. SingletonFactories is a Map, the key is beanName, and the value is ObjectFactory type (actually it is A lambda expression), when the getObject() method of ObjectFactory is called, the method body of the lambda expression will be executed. In the current scenario, the post processor of the Bean is actually executed once.
  4. populateBean(beanName, mbd, instanceWrapper); //Fill in the properties. The post processor will be executed twice.
    1. The post processor is called for the first time: InstantiationAwareBeanPostProcessor.postProcessAfterInstantiation(): Determine whether the bean should be filled with attributes, if it returns false, the method ends directly.
    2. The second call to the post processor: InstantiationAwareBeanPostProcessor.postPropertyValues(): Fill in the properties and complete the assembly.
      1. Protagonists: AutowiredAnnotationBeanPostProcessor, CommonAnnotationBeanPostBeanPostProcessor, they are automatically assembled according to the annotation information previously cached in injectionMetadataCache.
  5. initializeBean(beanName, exposedObject, mbd); //Initialize bean. Initialize related methods for Bean callback and call the post processor twice.
    1. Execute the invokeAwareMethods() method (that is, the method that executes the Aware interface), such as: BeanNameAware, BeanClassLoaderAware, BeanFactoryAware. Set the name of the bean, bean class loader, beanFactory
    2. BeanPostProcessor.postProcessBeforeInilization(). All Beans will go to this post processor.
    3. invokeInitMethods()
      1. The afterPropertiesSet() method specified for the bean. This method belongs to the InilizaingBean interface
      2. The initMethod() method specified for the bean. This method belongs to the InilizaingBean interface
    4. BeanPostProcessor.postProcessAfterInilization()
  6. So far, the bean instantiation and initialization process has been completed, and the created bean will be returned. If it is a singleton bean, it will finally be stored in the singletonObjects of the DefaultSingletonBeanRegistry.

code of doCreateBean() method

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, 
                              final @Nullable Object[] args) throws BeanCreationException {
    // Instantiate the bean.
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 实例化bean(第二次执行后置处理器的入口),第二次执行后置处理器,主要是为了推断出实例化Bean所需要的构造器
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = instanceWrapper.getWrappedInstance();
    Class<?> beanType = instanceWrapper.getWrappedClass();
    if (beanType != NullBean.class) {
        mbd.resolvedTargetType = beanType;
    }
    // 此时bean对象已经创建成功,但是没有设置属性和经过其他后置处理器处理
    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                // 第三次执行后置处理器,缓存bean的注解元数据信息(用于后面在进行属性填充时使用)
                // 这一步对于CommonAnnotationBeanPostProcessor、AutowiredAnnotationBeanPostProcessor、
                //     RequiredAnnotationBeanPostProcessor这一类处理器
                // 主要是将bean的注解信息解析出来,然后缓存到后置处理器中的injectionMetadataCache属性中
                // ApplicationListenerDetector将bean是否是单例的标识存于singletonNames这个Map类型的属性中
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            mbd.postProcessed = true;
        }
    }
    // 判断一个bean是否放入到singletonFactories中(提前暴露出来,可以解决循环依赖的问题)
    boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
            isSingletonCurrentlyInCreation(beanName));
    if (earlySingletonExposure) {
        // 第四次出现后置处理器
        // 获取提前暴露的对象,可以解决循环引用的问题,实际上提前暴露出来的bean是放入到了singletonFactories中,
        //       key是beanName,value是一个lambda表达式
        addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
    }
    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        // 填充属性,第五次、第六次后置处理器入口
        populateBean(beanName, mbd, instanceWrapper);
        // 第七次、第八次执行后置处理器入口
        exposedObject = initializeBean(beanName, exposedObject, mbd);
    }
    catch (Throwable ex) {
    }
    return exposedObject;
}

 

Guess you like

Origin blog.csdn.net/feiying0canglang/article/details/114555910