1. 程式人生 > >Spring加載流程源碼分析03【refresh】

Spring加載流程源碼分析03【refresh】

國際 並保存 webapp 優先級 get() ram ase urn continue

??前面兩篇文章分析了super(this)和setConfigLocations(configLocations)的源代碼,本文來分析下refresh的源碼,

Spring加載流程源碼分析01【super】
Spring加載流程源碼分析02【setConfigLocations】

先來看下ClassPathXmlApplicationContext類的初始化過程:

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
        throws BeansException {
    super(parent);
    setConfigLocations(configLocations);
    if (refresh) {
        refresh();
    }
}

refresh介紹

??refresh方法的具體實現是在AbstractApplicationContext類中如下:

@Override
public void refresh() throws BeansException, IllegalStateException {
    //startupShutdownMonitor對象在spring環境刷新和銷毀的時候都會用到,確保刷新和銷毀不會同時執行
    synchronized (this.startupShutdownMonitor) {
        // 準備工作,例如記錄事件,設置標誌,檢查環境變量等,並有留給子類擴展的位置,用來將屬性加入到applicationContext中
        prepareRefresh();

        // 創建beanFactory,這個對象作為applicationContext的成員變量,可以被applicationContext拿來用,
        // 並且解析資源(例如xml文件),取得bean的定義,放在beanFactory中
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // 對beanFactory做一些設置,例如類加載器、SPEL解析器、指定bean的某些類型的成員變量對應某些對象.
        prepareBeanFactory(beanFactory);

        try {
            // 子類擴展用,可以設置bean的後置處理器(bean在實例化之後這些後置處理器會執行)
            postProcessBeanFactory(beanFactory);

            // 執行beanFactory後置處理器(有別於bean後置處理器處理bean實例,beanFactory後置處理器處理bean定義)
            invokeBeanFactoryPostProcessors(beanFactory);

            // 將所有的bean的後置處理器排好序,但不會馬上用,bean實例化之後會用到
            registerBeanPostProcessors(beanFactory);

            // 初始化國際化服務
            initMessageSource();

            // 創建事件廣播器
            initApplicationEventMulticaster();

            // 空方法,留給子類自己實現的,在實例化bean之前做一些ApplicationContext相關的操作
            onRefresh();

            // 註冊一部分特殊的事件監聽器,剩下的只是準備好名字,留待bean實例化完成後再註冊
            registerListeners();

            // 單例模式的bean的實例化、成員變量註入、初始化等工作都在此完成
            finishBeanFactoryInitialization(beanFactory);

            // applicationContext刷新完成後的處理,例如生命周期監聽器的回調,廣播通知等
            finishRefresh();
        }

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

            // 刷新失敗後的處理,主要是將一些保存環境信息的集合做清理
            destroyBeans();

            // applicationContext是否已經激活的標誌,設置為false
            cancelRefresh(ex);

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

接下來一一介紹下

1.prepareRefresh介紹

protected void prepareRefresh() {
    // 設置初始化開始的時間
    this.startupDate = System.currentTimeMillis();
    // 設置context的關閉狀態為false
    this.closed.set(false);
    // 設置context的活動狀態是true
    this.active.set(true);

    if (logger.isInfoEnabled()) {
        logger.info("Refreshing " + this);
    }

    // Initialize any placeholder property sources in the context environment
    // 留個子類自己實現的空方法
    initPropertySources();

    // 驗證對應的key在環境變量中是否存在,如果不存在就拋異常
    getEnvironment().validateRequiredProperties();

    // earlyApplicationEvents存放早起的一些事件。
    this.earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>();
}

initPropertySources() 留給子類實現的方法

protected void initPropertySources() {
    // For subclasses: do nothing by default.
}

2.obtainFreshBeanFactory()介紹

創建了一個BeanFactory對象

/**
 * Tell the subclass to refresh the internal bean factory.
 * 子類實現
 * @return the fresh BeanFactory instance
 * @see #refreshBeanFactory()
 * @see #getBeanFactory()
 */
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    // 子類(AbstractRefreshableApplicationContext)創建一個ConfigurableListableBeanFactory 對象
    refreshBeanFactory();
    // 獲取refreshBeanFactory()實現類中創建的BeanFactory對象
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (logger.isDebugEnabled()) {
        logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
    }
    return beanFactory;
}

refreshBeanFactory()

該方法是子類實現的方法,在AbstractRefreshableApplicationContext類中該方法創建了ConfigurableListableBeanFactory 對象並且完成了,並賦值給了beanFactory

@Override
protected final void refreshBeanFactory() throws BeansException {
    // 如果BeanFactory存在就銷毀
    if (hasBeanFactory()) {
        destroyBeans();
        closeBeanFactory();
    }
    try {
        DefaultListableBeanFactory beanFactory = createBeanFactory();
        // BeanFactory的初始化操作
        beanFactory.setSerializationId(getId());
        customizeBeanFactory(beanFactory);
        // 在次方法中完成了application.xml文件的解析
        loadBeanDefinitions(beanFactory);
        synchronized (this.beanFactoryMonitor) {
            // 創建的對象賦值給了成員變量beanFactory
            this.beanFactory = beanFactory;
        }
    }
    catch (IOException ex) {
        throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    }
}

進入loadBeanDefinitions(beanFactory)方法查看

protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
    // Create a new XmlBeanDefinitionReader for the given BeanFactory.
    XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

    // Configure the bean definition reader with this context's
    // resource loading environment.
    beanDefinitionReader.setEnvironment(getEnvironment());
    beanDefinitionReader.setResourceLoader(this);
    beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

    // Allow a subclass to provide custom initialization of the reader,
    // then proceed with actually loading the bean definitions.
    initBeanDefinitionReader(beanDefinitionReader);
    // 進入該方法查看
    loadBeanDefinitions(beanDefinitionReader);
}

loadBeanDefinitions(beanDefinitionReader);

protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws IOException {
    String[] configLocations = getConfigLocations();
    if (configLocations != null) {
        for (String configLocation : configLocations) {
            //繼續進入 configLocation 是applicationContext.xml
            reader.loadBeanDefinitions(configLocation);
        }
    }
}

進入跟蹤

public int loadBeanDefinitions(String location, Set<Resource> actualResources) throws BeanDefinitionStoreException {
    //這是我們在前面文章中初始的ResourceLoader對象
    ResourceLoader resourceLoader = getResourceLoader();
    if (resourceLoader == null) {
        throw new BeanDefinitionStoreException(
                "Cannot import bean definitions from location [" + location + "]: no ResourceLoader available");
    }

    if (resourceLoader instanceof ResourcePatternResolver) {
        // Resource pattern matching available.
        try {
            Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
            // 此處進入
            int loadCount = loadBeanDefinitions(resources);
            if (actualResources != null) {
                for (Resource resource : resources) {
                    actualResources.add(resource);
                }
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Loaded " + loadCount + " bean definitions from location pattern [" + location + "]");
            }
            return loadCount;
        }
        catch (IOException ex) {
            throw new BeanDefinitionStoreException(
                    "Could not resolve bean definition resource pattern [" + location + "]", ex);
        }
    }
    else {
        // Can only load single resources by absolute URL.
        Resource resource = resourceLoader.getResource(location);
        int loadCount = loadBeanDefinitions(resource);
        if (actualResources != null) {
            actualResources.add(resource);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("Loaded " + loadCount + " bean definitions from location [" + location + "]");
        }
        return loadCount;
    }
}

繼續跟蹤

public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
    Assert.notNull(encodedResource, "EncodedResource must not be null");
    if (logger.isInfoEnabled()) {
        logger.info("Loading XML bean definitions from " + encodedResource.getResource());
    }

    Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
    if (currentResources == null) {
        currentResources = new HashSet<EncodedResource>(4);
        this.resourcesCurrentlyBeingLoaded.set(currentResources);
    }
    if (!currentResources.add(encodedResource)) {
        throw new BeanDefinitionStoreException(
                "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
    }
    try {
        // 獲取applicationContext.xml對應的字節輸入流
        InputStream inputStream = encodedResource.getResource().getInputStream();
        try {
            InputSource inputSource = new InputSource(inputStream);
            if (encodedResource.getEncoding() != null) {
                inputSource.setEncoding(encodedResource.getEncoding());
            }
            // 將配置文件中的信息加載到定義的bean中
            return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
        }
        finally {
            inputStream.close();
        }
    }
    catch (IOException ex) {
        throw new BeanDefinitionStoreException(
                "IOException parsing XML document from " + encodedResource.getResource(), ex);
    }
    finally {
        currentResources.remove(encodedResource);
        if (currentResources.isEmpty()) {
            this.resourcesCurrentlyBeingLoaded.remove();
        }
    }
}

跟蹤到如下代碼

try {
    Document doc = doLoadDocument(inputSource, resource);
    return registerBeanDefinitions(doc, resource);
}

技術分享圖片
上面是加載bean定義的關鍵代碼:先制作Document對象,再調用registerBeanDefinitions方法,最終會將每個bean的定義放入DefaultListableBeanFactory的beanDefinitionMap中。

getBeanFactory()

獲取refreshBeanFactory()實現類中創建的BeanFactory對象

@Override
public final ConfigurableListableBeanFactory getBeanFactory() {
    synchronized (this.beanFactoryMonitor) {
        if (this.beanFactory == null) {
            throw new IllegalStateException("BeanFactory not initialized or already closed - " +
                    "call 'refresh' before accessing beans via the ApplicationContext");
        }
        return this.beanFactory;
    }
}

3.prepareBeanFactory

BeanFactory的預準備工作

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 1)、設置BeanFactory的類加載器
    beanFactory.setBeanClassLoader(getClassLoader());
    // 1)、設置支持表達式解析器
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
?
    // 2)、添加部分BeanPostProcessor【ApplicationContextAwareProcessor】
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    // 3)、設置忽略的自動裝配的接口EnvironmentAware、EmbeddedValueResolverAware、xxx;
   // 這些接口的實現類不能通過類型來自動註入
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
?
    // 4)、註冊可以解析的自動裝配;我們能直接在任何組件中自動註入:
    //BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
    /* 其他組件中可以通過下面方式直接註冊使用
    @autowired 
    BeanFactory beanFactory */
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);
?
    // 5)、添加BeanPostProcessor【ApplicationListenerDetector】後置處理器,在bean初始化前後的一些工作
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));
?
    // 6)、添加編譯時的AspectJ;
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        // Set a temporary ClassLoader for type matching.
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
?
    // 7)、給BeanFactory中註冊一些能用的組件;
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
    // 環境信息ConfigurableEnvironment
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    //系統屬性,systemProperties【Map<String, Object>】
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    //系統環境變量systemEnvironment【Map<String, Object>】
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

prepareBeanFactory方法就是為beanFactory做一些設置工作,傳入一些後面會用到的參數和工具類,再在spring容器中創建一些bean;

4.postProcessBeanFactory

postProcessBeanFactory方法是留給子類擴展的,可以在bean實例初始化之前註冊後置處理器(類似prepareBeanFactory方法中的beanFactory.addBeanPostProcessor),以子類AbstractRefreshableWebApplicationContext為例,其postProcessBeanFactory方法

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
    beanFactory.ignoreDependencyInterface(ServletContextAware.class);
    beanFactory.ignoreDependencyInterface(ServletConfigAware.class);

    WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
    WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}

除了WebApplicationContextUtils類的工作之外,其余的都是和prepareBeanFactory方法中類似的處理

5.invokeBeanFactoryPostProcessors

nvokeBeanFactoryPostProcessors方法用來執行BeanFactory實例的後置處理器BeanFactoryPostProcessor的postProcessBeanFactory方法,這個後置處理器除了原生的,我們也可以自己擴展,用來對Bean的定義做一些修改,由於此時bean還沒有實例化,所以不要在自己擴展的BeanFactoryPostProcessor中調用那些會觸發bean實例化的方法(例如BeanFactory的getBeanNamesForType方法),源碼的文檔中有相關說明,不要觸發bean的實例化,如果要處理bean實例請在BeanPostProcessor中進行;
技術分享圖片

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

    // Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
    // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
}

6.registerBeanPostProcessors

registerBeanPostProcessors方法的代碼略多,就不在此貼出來了,簡單的說,就是找出所有的bean的後置處理器(註意,是bean的後置處理器,不是beanFactory的後置處理器,bean後置處理器處理的是bean實例,beanfactory後置處理器處理的是bean的定義),然後將這些bean的後置處理器分為三類:

  1. 實現了順序接口Ordered.class的,先放入orderedPostProcessors集合,排序後順序加入beanFactory的bean後處理集合中;
  2. 既沒有實現Ordered.class,也沒有實現PriorityOrdered.class的後置處理器,也加入到beanFactory的bean後處理集合中;
  3. 最後是實現了優先級接口PriorityOrdered.class的,排序後順序加入beanFactory的bean後處理集合中;

registerBeanPostProcessors方法執行完畢後,beanFactory中已經保存了有序的bean後置處理器,在bean實例化之後,會依次使用這些後置處理器對bean實例來做對應的處理;
技術分享圖片

7.initMessageSource

initMessageSource方法用來準備國際化資源相關的,將實現了MessageSource接口的bean存放在ApplicationContext的成員變量中,先看是否有配置,如果有就實例化,否則就創建一個DelegatingMessageSource實例的bean

8.initApplicationEventMulticaster

spring中有事件、事件廣播器、事件監聽器等組成事件體系,在initApplicationEventMulticaster方法中對事件廣播器做初始化,如果找不到此bean的配置,就創建一個SimpleApplicationEventMulticaster實例作為事件廣播器的bean,並且保存為applicationContext的成員變量applicationEventMulticaster

/**
 * Initialize the ApplicationEventMulticaster.
 * Uses SimpleApplicationEventMulticaster if none defined in the context.
 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
 */
protected void initApplicationEventMulticaster() {
    //獲取BeanFactory
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    // 判斷是否存在
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        // 從容器中獲取ApplicationEventMulticaster對象
        this.applicationEventMulticaster =
                beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isDebugEnabled()) {
            logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    else {
        // 初始一個SimpleApplicationEventMulticaster對象
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        // 創建的對象註冊到BeanFactory中
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isDebugEnabled()) {
            logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                    APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                    "': using default [" + this.applicationEventMulticaster + "]");
        }
    }
}

9.onRefresh

onRefresh是個空方法,留給子類自己實現的,在實例化bean之前做一些ApplicationContext相關的操作,以子類AbstractRefreshableWebApplicationContext為例,看看它的onRefresh方法

/**
 * Initialize the theme capability.
 */
@Override
protected void onRefresh() {
    this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}

10.registerListeners

方法名為registerListeners,看名字像是將監聽器註冊在事件廣播器中,但實際情況並非如此,只有一些特殊的監聽器被註冊了,那些在bean配置文件中實現了ApplicationListener接口的類還沒有實例化,所以此處只是將其name保存在廣播器中,將這些監聽器註冊在廣播器的操作是在bean的後置處理器中完成的,那時候bean已經實例化完成了,我們看代碼

protected void registerListeners() {
    // 註冊的都是特殊的事件監聽器,而並非配置中的bean
    for (ApplicationListener<?> listener : getApplicationListeners()) {
        getApplicationEventMulticaster().addApplicationListener(listener);
    }

    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let post-processors apply to them!
    // 根據接口類型找出所有監聽器的名稱
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    for (String listenerBeanName : listenerBeanNames) {
        // 這裏只是把監聽器的名稱保存在廣播器中,並沒有將這些監聽器實例化!!!
        getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }
}

11.finishBeanFactoryInitialization

finishBeanFactoryInitialization方法做了兩件事:

  1. beanFactory對象的初始化;
  2. 我們在bean配置文件中配置的那些單例的bean,都是在finishBeanFactoryInitialization方法中實例化的;
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // Initialize conversion service for this context.
    // 實例化類型轉換的bean,並保存在ApplicationContext中
    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));
    }

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    // 實例化LoadTimeWeaverAware接口的bean,用於ApsectJ的類加載期織入的處理
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    // Stop using the temporary ClassLoader for type matching.
    // 確保臨時的classLoader為空,臨時classLoader一般被用來做類型匹配的
    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    // 將一個標誌設置為true,表示applicationContext已經緩存了所有bean的定義,這些bean的name都被保存在applicationContext的frozenBeanDefinitionNames成員變量中,相當於一個快照,記錄了當前那些bean的定義已經拿到了
    beanFactory.freezeConfiguration();

    // 實例化所有還未實例化的單例bean
    beanFactory.preInstantiateSingletons();
}

preInstantiateSingletons方法

public void preInstantiateSingletons() throws BeansException {
        if (this.logger.isDebugEnabled()) {
            this.logger.debug("Pre-instantiating singletons in " + this);
        }

        // Iterate over a copy to allow for init methods which in turn register new bean definitions.
        // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
        List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

        // Trigger initialization of all non-lazy singleton beans...
        for (String beanName : beanNames) {
            // 獲取bean的定義,該定義已經和父類定義做了合並
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            // 非抽象類、是單例、非懶加載
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                //FactoryBean的處理
                if (isFactoryBean(beanName)) {
                    final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
                            @Override
                            public Boolean run() {
                                return ((SmartFactoryBean<?>) factory).isEagerInit();
                            }
                        }, getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
                else {
                    //非FactoryBean的實例化、初始化
                    getBean(beanName);
                }
            }
        }

        // Trigger post-initialization callback for all applicable beans...
        // 單例實例化完成後,如果實現了SmartInitializingSingleton接口,afterSingletonsInstantiated就會被調用,此處用到了特權控制邏輯AccessController.doPrivileged
        for (String beanName : beanNames) {
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction<Object>() {
                        @Override
                        public Object run() {
                            smartSingleton.afterSingletonsInstantiated();
                            return null;
                        }
                    }, getAccessControlContext());
                }
                else {
                    smartSingleton.afterSingletonsInstantiated();
            }
        }
    }
}

技術分享圖片
doGetBean

protected <T> T doGetBean(
    final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
    throws BeansException {
?
    final String beanName = transformedBeanName(name);
    Object bean;
?
/**
2、先獲取緩存中保存的單實例Bean。如果能獲取到說明這個Bean之前被創建過(所有創建過的單實例Bean都會被緩存起來)
從private final Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);獲取的
 **/
    Object sharedInstance = getSingleton(beanName);
    //如果沒有獲取到創建bean 
    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 + "'");
            }
        }
        bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
    }
?
    else {//3、緩存中獲取不到,開始Bean的創建對象流程;
        // Fail if we're already creating this bean instance:
        // We're assumably within a circular reference.
        if (isPrototypeCurrentlyInCreation(beanName)) {
            throw new BeanCurrentlyInCreationException(beanName);
        }
?
        //  獲取父beanFatory 檢查這個bean是否創建了
        BeanFactory parentBeanFactory = getParentBeanFactory();
        if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
            // Not found -> check parent.
            String nameToLookup = originalBeanName(name);
            if (args != null) {
                return (T) parentBeanFactory.getBean(nameToLookup, args);
            }
            else {   
                return parentBeanFactory.getBean(nameToLookup, requiredType);
            }
        }
?
        // 4、標記當前bean已經被創建
        if (!typeCheckOnly) {
            markBeanAsCreated(beanName);
        }
?
        try {
            // 5、獲取Bean的定義信息;
            final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
            checkMergedBeanDefinition(mbd, beanName, args);
?
            // 6、【獲取當前Bean依賴的其他Bean;如果有按照getBean()把依賴的Bean先創建出來;】
            String[] dependsOn = mbd.getDependsOn();
            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 + "'");
                    }
                    registerDependentBean(dep, beanName);
                    getBean(dep); //先創建依賴的bean
                }
            }
?
            // 啟動單實例的bean的創建流程
            if (mbd.isSingleton()) {
                //獲取到單實例bean後,添加到緩存中 singletonObjects()
      //Map<String, Object> singletonObjects = new ConcurrentHashMap<String, Object>(256);
                sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
                    @Override
                    public Object getObject() throws BeansException {
                        try {
                            //創建Bean
                            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, new ObjectFactory<Object>() {
                        @Override
                        public Object getObject() throws BeansException {
                            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;
        }
    }
?
    // Check if required type matches the type of the actual bean instance.
    if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
        try {
            return getTypeConverter().convertIfNecessary(bean, requiredType);
        }
        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;
}

doCreateBean方法

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args)
    throws BeanCreationException {
?
    // bean的包裝
    BeanWrapper instanceWrapper = null;
    if (mbd.isSingleton()) {
        instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
    }
    if (instanceWrapper == null) {
        // 1)、【創建Bean實例】利用工廠方法或者對象的構造器創建出Bean實例;
        instanceWrapper = createBeanInstance(beanName, mbd, args);
    }
    final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
    Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);
    mbd.resolvedTargetType = beanType;
?
    // Allow post-processors to modify the merged bean definition.
    synchronized (mbd.postProcessingLock) {
        if (!mbd.postProcessed) {
            try {
                //調用MergedBeanDefinitionPostProcessor的postProcessMergedBeanDefinition(mbd, beanType, beanName);
                //判斷是否為:MergedBeanDefinitionPostProcessor 類型的,如果是,調用方法
                //MergedBeanDefinitionPostProcessor 後置處理器是在bean實例換之後調用的
                applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
            }
            catch (Throwable ex) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                                "Post-processing of merged bean definition failed", ex);
            }
            mbd.postProcessed = true;
        }
    }
?
    //判斷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到緩存中
        addSingletonFactory(beanName, new ObjectFactory<Object>() {
            @Override
            public Object getObject() throws BeansException {
                return getEarlyBeanReference(beanName, mbd, bean);
            }
        });
    }
?
    // Initialize the bean instance.
    Object exposedObject = bean;
    try {
        //為bean 賦值
        populateBean(beanName, mbd, instanceWrapper);
        if (exposedObject != null) {
            // 4)、【Bean初始化】
            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) {
        //獲取單實例bean,此時已經創建好了
        Object earlySingletonReference = getSingleton(beanName, false);
        if (earlySingletonReference != null) {
            if (exposedObject == bean) {
                exposedObject = earlySingletonReference;
            }
            else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                String[] dependentBeans = getDependentBeans(beanName);
                Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
                for (String dependentBean : dependentBeans) {
                    if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                        actualDependentBeans.add(dependentBean);
                    }
                }
                if (!actualDependentBeans.isEmpty()) {
                    throw new BeanCurrentlyInCreationException(beanName,
                                                               "Bean with name '" + beanName + "' has been injected into other beans [" +
                                                               StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                                               "] in its raw version as part of a circular reference, but has eventually been " +
                                                               "wrapped. This means that said other beans do not use the final version of the " +
                                                               "bean. This is often the result of over-eager type matching - consider using " +
                                                               "'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
                }
            }
        }
    }
?
    //  5)、註冊實現了DisposableBean 接口Bean的銷毀方法;只是註冊沒有去執行,容器關閉之後才去調用的
    try {
        registerDisposableBeanIfNecessary(beanName, bean, mbd);
    }
    catch (BeanDefinitionValidationException ex) {
        throw new BeanCreationException(
            mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
    }
?
    return exposedObject;
}

populateBean()創建bean後屬性賦值

//populateBean():1204, AbstractAutowireCapableBeanFactory 
protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
    PropertyValues pvs = mbd.getPropertyValues();
?
    if (bw == null) {
        if (!pvs.isEmpty()) {
            throw new BeanCreationException(
                mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
        }
        else {
            // Skip property population phase for null instance.
            return;
        }
    }
?
    // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
    // state of the bean before properties are set. This can be used, for example,
    // to support styles of field injection.
    boolean continueWithPropertyPopulation = true;
?
    //賦值之前:
    /* 1)、拿到InstantiationAwareBeanPostProcessor後置處理器;
        執行處理器的postProcessAfterInstantiation(); 方法*/
    if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
        for (BeanPostProcessor bp : getBeanPostProcessors()) {
            if (bp instanceof InstantiationAwareBeanPostProcessor) {
                InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                //執行
                if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                    continueWithPropertyPopulation = false;
                    break;
                }
            }
        }
    }
?
    if (!continueWithPropertyPopulation) {
        return;
    }
?
    if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
        mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
        MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
?
        // autowire  按name註入
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
            autowireByName(beanName, mbd, bw, newPvs);
        }
?
        // autowire  按類型註入
        if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
            autowireByType(beanName, mbd, bw, newPvs);
        }
?
        pvs = newPvs;
    }
?
    boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
    boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);
/*2)、拿到InstantiationAwareBeanPostProcessor後置處理器;
    執行 postProcessPropertyValues(); 獲取到屬性的值,此時還未賦值*/
    if (hasInstAwareBpps || needsDepCheck) {
        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) {
            checkDependencies(beanName, mbd, filteredPds, pvs);
        }
    }
//=====賦值之前:===  
//3)、應用Bean屬性的值;為屬性利用setter方法等進行賦值;
    applyPropertyValues(beanName, mbd, bw, pvs);
}

Bean初始化 initializeBean

//初始化
protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
    if (System.getSecurityManager() != null) {
        AccessController.doPrivileged(new PrivilegedAction<Object>() {
            @Override
            public Object run() {
                invokeAwareMethods(beanName, bean);
                return null;
            }
        }, getAccessControlContext());
    }
    else {
        //1)、【執行Aware接口方法】invokeAwareMethods(beanName, bean);執行xxxAware接口的方法
        //判斷是否實現了 BeanNameAware\BeanClassLoaderAware\BeanFactoryAware 這些接口的bean,如果是執行相應的方法
        invokeAwareMethods(beanName, bean);
    }
?
    Object wrappedBean = bean;
    if (mbd == null || !mbd.isSynthetic()) {
        //2)、【執行後置處理器BeanPostProcessor初始化之前】 執行所有的 BeanPostProcessor.postProcessBeforeInitialization();
        wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
    }
?
    try {
        //3)、【執行初始化方法】
        invokeInitMethods(beanName, wrappedBean, mbd);
    }
    catch (Throwable ex) {
        throw new BeanCreationException(
            (mbd != null ? mbd.getResourceDescription() : null),
            beanName, "Invocation of init method failed", ex);
    }
    //4)、【執行後置處理器初始化之後】 執行所有的beanProcessor.postProcessAfterInitialization(result, beanName);方法
    if (mbd == null || !mbd.isSynthetic()) {
        wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
    }
    return wrappedBean;
}

執行bean的初始化方法init
1)是否是InitializingBean接口的實現;執行接口規定的初始化;
2)是否自定義初始化方法;通過註解的方式添加了initMethod方法的,

? 例如: @Bean(initMethod="init",destroyMethod="detory")

//invokeInitMethods():1667, AbstractAutowireCapableBeanFactory  
protected void invokeInitMethods(String beanName, final Object bean, RootBeanDefinition mbd)
    throws Throwable {
//1)、是否是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(new PrivilegedExceptionAction<Object>() {
                    @Override
                    public Object run() throws Exception {
                        ((InitializingBean) bean).afterPropertiesSet();
                        return null;
                    }
                }, getAccessControlContext());
            }
            catch (PrivilegedActionException pae) {
                throw pae.getException();
            }
        }
        else {
            //執行實現InitializingBean的afterPropertiesSet方法
            ((InitializingBean) bean).afterPropertiesSet();
        }
    }
?
    if (mbd != null) {
        //執行通過註解自定義的initMethod 方法
        String initMethodName = mbd.getInitMethodName();
        if (initMethodName != null && !(isInitializingBean && "afterPropertiesSet".equals(initMethodName)) &&
            !mbd.isExternallyManagedInitMethod(initMethodName)) {
            invokeCustomInitMethod(beanName, bean, mbd);
        }
    }
}

12.finishRefresh

最後一個方法是finishRefresh,這是在bean的實例化、初始化等完成後的一些操作,例如生命周期變更的回調,發送applicationContext刷新完成的廣播等,展開看看

protected void finishRefresh() {
    // 檢查是否已經配置了生命周期處理器,如果沒有就new一個DefaultLifecycleProcessor
    initLifecycleProcessor();

    // 找到所有實現了Lifecycle接口的bean,按照每個bean設置的生命周期階段進行分組,再依次調用每個分組中每個bean的start方法,完成生命周期監聽的通知
    getLifecycleProcessor().onRefresh();

    // 創建一條代表applicationContext刷新完成的事件,交給廣播器去廣播
    publishEvent(new ContextRefreshedEvent(this));

    // 如果配置了MBeanServer,就完成在MBeanServer上的註冊
    LiveBeansView.registerApplicationContext(this);
}

Spring啟動流程總結

  1. Spring容器在啟動的時候,先會保存所有註冊進來的Bean的定義信息;
    1.1 xml註冊bean;
    1.2 註解註冊Bean;@Service、@Component、@Bean、xxx
  2. Spring容器會合適的時機創建這些Bean
    2.1用到這個bean的時候;利用getBean創建bean;創建好以後保存在容器中;
    2.2統一創建剩下所有的bean的時候;finishBeanFactoryInitialization();
  3. 後置處理器;BeanPostProcessor
    每一個bean創建完成,都會使用各種後置處理器進行處理;來增強bean的功能;
    AutowiredAnnotationBeanPostProcessor:處理自動註入
    AnnotationAwareAspectJAutoProxyCreator:來做AOP功能;
  4. 事件驅動模型;
    ApplicationListener;事件監聽;
    ApplicationEventMulticaster;事件派發:

Spring加載流程源碼分析03【refresh】