Spring源碼解析-實例化bean對象


  

  spring加載配置文件,AbstractApplicationContext類中的refresh方法起着重要的作用。

@Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            // Prepare this context for refreshing.准備刷新context
            prepareRefresh();

            // Tell the subclass to refresh the internal bean factory.刷新子類beanFactory,注冊beanDefinition
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            // Prepare the bean factory for use in this context.准備beanfactory
            prepareBeanFactory(beanFactory);

            try {
                // Allows post-processing of the bean factory in context subclasses.
                postProcessBeanFactory(beanFactory);

                // Invoke factory processors registered as beans in the context.
                invokeBeanFactoryPostProcessors(beanFactory);

                // Register bean processors that intercept bean creation.
                registerBeanPostProcessors(beanFactory);

                // Initialize message source for this context.
                initMessageSource();

                // Initialize event multicaster for this context.
                initApplicationEventMulticaster();

                // Initialize other special beans in specific context subclasses.
                onRefresh();

                // Check for listener beans and register them.
                registerListeners();

                // Instantiate all remaining (non-lazy-init) singletons.初始化非懶加載的bean實例
                finishBeanFactoryInitialization(beanFactory);

                // Last step: publish corresponding event.
                finishRefresh();
            }

            catch (BeansException ex) {
                logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);

                // Destroy already created singletons to avoid dangling resources.
                destroyBeans();

                // Reset 'active' flag.
                cancelRefresh(ex);

                // Propagate exception to caller.
                throw ex;
            }
        }
    }

實例化bean對象,主要的是在

finishBeanFactoryInitialization(beanFactory)

 方法。
大致的流程圖(下部分):

 

點擊查看大圖

下面分析實例化bean對象的源碼分析

加載bean對象:

 

AbstractBeanFactory類中,根據不同scope進行實例化,例如Singleton,Prototype

 

 

 

 

 

 

根據不同情況采用不同的代理方式:

到這里就是bean實例的初始化,可以看到spring采用的代理方式,來實現bean的初始化。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM