Spring IoC 容器的擴展

前言

本系列全部基于 Spring 5.2.2.BUILD-SNAPSHOT 版本。因為 Spring 整個體系太過于龐大,所以只會進行關鍵部分的源碼解析。

本篇文章主要介紹 Spring IoC 容器的功能擴展。

正文

我們平時在使用 Spring 時,大多不會直接使用 BeanFactory,使用比較多的是 ApplicationContext;那么在 Spring 中 BeanFactoryApplicationContext 有什么區別呢?

  • BeanFactory 這個接口提供了高級配置的機制的管理對象,是一個基本的 IoC 的容器。
  • ApplicationContextBeanFactory 的一個子接口,提供了 BeanFactory 的全部功能,并且在此基礎上還提供了:
    • 面向切面 (AOP)
    • 配置元信息 (Configuration Metadata)
    • 資源管理 (Resources)
    • 事件 (Events)
    • 國際化 (i18n)
    • 注解 (Annotations)
    • Environment 抽象 (Environment Abstraction)

真正的底層 IoC 容器是 BeanFactory 的實現類,ApplicationContext 中的 getBean() 其實都是委托給 DefaultListableBeanFactory 來實現。

其中核心流程都在 AbstractApplicationContext#refresh() 方法中,我們直接從這個方法開始。

容器刷新

AbstractApplicationContext#refresh

public void refresh() throws BeansException, IllegalStateException {
    // 加鎖
    synchronized (this.startupShutdownMonitor) {
        // 準備刷新的上下文環境,見下文詳解
        prepareRefresh();

        // 獲取刷新后的beanFactory,一般都是創建一個DefaultListableBeanFactory,見下文詳解
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // 使用當前上下文環境準備beanFactory,見下文詳解
        prepareBeanFactory(beanFactory);

        try {
            // beanFactory的后置處理,子類實現,這也算是beanFactory的擴展點
            // AbstractRefreshableWebApplicationContext在這個方法內加入了request和session的作用域
            postProcessBeanFactory(beanFactory);

            // 調用所有BeanFactoryPostProcessors的實現類,見下文詳解
            invokeBeanFactoryPostProcessors(beanFactory);

            // 注冊BeanPostProcessors,見下文詳解
            registerBeanPostProcessors(beanFactory);

            // 初始化消息資源,這里不做過多分析
            initMessageSource();

            // 初始化事件傳播器,這里不做過多分析
            initApplicationEventMulticaster();

            // 在特殊的上下文環境中初始化指定的bean,模板方法留給子類實現
            onRefresh();

            // 注冊監聽器,這里不做過多分析
            registerListeners();

            // 實例化所有非延遲加載的單例bean,見下文詳解
            finishBeanFactoryInitialization(beanFactory);

            // 完成上下文的刷新,調用生命周期處理器的onRefresh()并且發布上下文刷新完成事件,這里不做過多分析
            finishRefresh();
        }
        // 省略異常處理
        finally {
            // 重置緩存,例如方法、字段等
            resetCommonCaches();
        }
    }
}

上面方法就是上下文刷新的流程, 其中關于消息資源和事件的處理這里就不分析了,后續可能會單獨分析一下 Spring 中的事件。

上下文刷新前的環境準備

AbstractApplicationContext#prepareRefresh

protected void prepareRefresh() {
    // 記錄開始時間
    this.startupDate = System.currentTimeMillis();
    // 上下文關閉標識設置為 false
    this.closed.set(false);
    // 上下文激活標識設置為 true
    this.active.set(true);

    // 初始化占位符屬性資源,該方法是留給子類實現的,默認什么也不做
    initPropertySources();

    // 驗證需要的屬性文件是否都已經放入環境中
    getEnvironment().validateRequiredProperties();

    if (this.earlyApplicationListeners == null) {
        this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    } else {
        // 在上下文刷新前重置監聽器
        this.applicationListeners.clear();
        this.applicationListeners.addAll(this.earlyApplicationListeners);
    }

    this.earlyApplicationEvents = new LinkedHashSet<>();
}

獲得新的 BeanFactory

AbstractApplicationContext#obtainFreshBeanFactory

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    // 刷新 bean 工廠,見下文詳解
    refreshBeanFactory(); 
    // 返回 bean 工廠,見下文詳解
    return getBeanFactory(); 
}

AbstractRefreshableApplicationContext#refreshBeanFactory

protected final void refreshBeanFactory() throws BeansException {
    // 如果有beanFactory
    if (hasBeanFactory()) {
        // 銷毀所有的單例bean
        destroyBeans();
        // 關閉beanFactory,也就是將beanFactory設置為null
        closeBeanFactory();
    }
    try {
        // 創建 DefaultListableBeanFactory
        DefaultListableBeanFactory beanFactory = createBeanFactory();
        // 指定序列化id
        beanFactory.setSerializationId(getId());
        // 定制beanFactory,設置相關屬性
        customizeBeanFactory(beanFactory);
        // 加載beanDefinition
        loadBeanDefinitions(beanFactory);
        synchronized (this.beanFactoryMonitor) {
            // 加鎖,將beanFactory賦值給全局變量
            this.beanFactory = beanFactory;
        }
    }
    // 省略異常處理...
}

AbstractRefreshableApplicationContext#getBeanFactory

public final ConfigurableListableBeanFactory getBeanFactory() {
    // 加鎖
    synchronized (this.beanFactoryMonitor) {
        // 如果beanFactory為空拋出異常
        if (this.beanFactory == null) {
            throw new IllegalStateException("BeanFactory not initialized or already closed - call 'refresh' before accessing beans via the ApplicationContext");
        }
        // 返回beanFactory
        return this.beanFactory;
    }
}

對 BeanFactory 進行功能填充

AbstractApplicationContext#prepareBeanFactory

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 設置beanFactory的classLoader為當前context的classLoader
    beanFactory.setBeanClassLoader(getClassLoader());
    // 設置beanFactory的表達式語言處理器
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    // 為beanFactory增加了一個的propertyEditor,這個主要是對bean的屬性等設置管理的一個工具
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // 添加bean擴展,主要是對ApplicationContext新增加的Aware接口進行調用
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

    // 設置幾個忽略自動裝配的接口
    beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
    beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
    beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
    beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
    beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

    // 注冊解決依賴,也就是說我們可以通過依賴注入來注入以下四種類型的bean
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // 將是ApplicationListener類型的bean在BeanPostProcessor的初始化后回調方法中加入到context的監聽器列表中
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // 增加對AspectJ支持
    if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }

    // 如果beanFactory不存在名為environment的bean,添加默認的,該bean就和我們正常聲明的單例bean一樣
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    // 如果beanFactory不存在名為systemProperties的bean,添加默認的,該bean就和我們正常聲明的單例bean一樣
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    // 如果systemEnvironment不存在名為systemEnvironment的bean,添加默認的,該bean就和我們正常聲明的單例bean一樣
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

調用 BeanFactory 的處理器

AbstractApplicationContext#invokeBeanFactoryPostProcessors

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    // 實例化并調用所有已注冊的BeanFactoryPostProcessor
    PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

    if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
        beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
        beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
    }
}

PostProcessorRegistryDelegate#invokeBeanFactoryPostProcessors

public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

    Set<String> processedBeans = new HashSet<>();
    // 判斷beanFactory是否是BeanDefinitionRegistry類型
    // 通常情況下這里的beanFactory是DefaultListableBeanFactory所以這里判斷為true
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        // 保存實現了BeanFactoryPostProcessor bean的集合
        List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
        // 保存實現了BeanDefinitionRegistryPostProcessor bean的集合
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
        // 遍歷beanFactoryPostProcessors
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            // 找出是BeanDefinitionRegistryPostProcessor類型的并調用其postProcessBeanDefinitionRegistry()
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                // 將BeanDefinitionRegistryPostProcessor類型的添加進registryProcessors
                registryProcessors.add(registryProcessor);
            }
            else {
                // 將BeanFactoryPostProcessor類型的添加進regularPostProcessors
                regularPostProcessors.add(postProcessor);
            }
        }

        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

        // 獲取所有BeanDefinitionRegistryPostProcessor類型的beanName
        String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        // 遍歷postProcessorNames
        for (String ppName : postProcessorNames) {
            // 如果實現了PriorityOrdered接口,
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                // 初始化此bean并添加進currentRegistryProcessors
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                // 將此beanName添加到已處理的記錄中
					processedBeans.add(ppName);
            }
        }
        // 排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        // 將所有BeanDefinitionRegistryPostProcessor類型并且實現了PriorityOrdered接口的bean添加進registryProcessors
        registryProcessors.addAll(currentRegistryProcessors);
        // 遍歷調用currentRegistryProcessors中的所有BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry()
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        // 清空currentRegistryProcessors
        currentRegistryProcessors.clear();

        // 和上面的差不多只是這次是實現了Ordered接口的,并且沒有處理過的
        postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                processedBeans.add(ppName);
            }
        }
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        registryProcessors.addAll(currentRegistryProcessors);
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        currentRegistryProcessors.clear();

        // 和上面的差不多只是這次是所有的實現了BeanDefinitionRegistryPostProcessors的bean,并且沒有處理過的
        boolean reiterate = true;
        while (reiterate) {
            reiterate = false;
            postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
            for (String ppName : postProcessorNames) {
                if (!processedBeans.contains(ppName)) {
                    currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                    processedBeans.add(ppName);
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }

        // 調用BeanFactoryPostProcessor的postProcessBeanFactory()
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }
    else {
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }

    // 獲取所有BeanFactoryPostProcessor類型的beanName
    String[] postProcessorNames =
        beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    // 遍歷postProcessorNames
    for (String ppName : postProcessorNames) {
        // 如果已經處理過,直接跳過;因為BeanDefinitionRegistryPostProcessor繼承于BeanFactoryPostProcessor
        // 所以postProcessorNames也包含BeanDefinitionRegistryPostProcessor類型的bean,這里會對BeanDefinitionRegistryPostProcessor類型的bean直接跳過
        if (processedBeans.contains(ppName)) {
        }
        // 如果實現了PriorityOrdered接口,初始化該bean并添加進priorityOrderedPostProcessors
        else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
        // 如果實現了Ordered接口,將beanName添加進orderedPostProcessorNames
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        // 正常的將beanName添加進nonOrderedPostProcessorNames
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // 排序,然后調用BeanFactoryPostProcessors的postProcessBeanFactory()
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // 和上面的一樣這里是實現了Ordered接口的
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // 和上面的一樣這里是正常的BeanFactoryPostProcessors
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

    beanFactory.clearMetadataCache();
}

上面代碼首先找出 BeanDefinitionRegistryPostProcessorBeanFactoryPostProcessor 類型的 bean,然后根據其實現的排序接口,來分別進行初始化以及調用其回調方法。可以把 PriorityOrdered 理解為 超級會員Ordered普通會員,都未實現的理解為 普通用戶,優先級一個比一個高。

我們首先看一下 BeanFactoryPostProcessor 接口的定義:

@FunctionalInterface
public interface BeanFactoryPostProcessor {

    /**
     * 容器初始化后,bean實例化之前調用,可以在此修改BeanDefinition
     */
    void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

可以看出 BeanFactoryPostProcessor 接口是 Spring 初始化 BeanFactory 時對外暴露的擴展點,Spring IoC 容器允許 BeanFactoryPostProcessor 在容器實例化任何 bean 之前讀取 bean 的定義,并可以修改它。

接下里我們看一下 BeanDefinitionRegistryPostProcessor 接口的定義:

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

BeanDefinitionRegistryPostProcessorBeanFactoryPostProcessor 具有更高的優先級,從上面解析的代碼中就可以看出,主要用來在 BeanFactoryPostProcessor 之前注冊其它 bean 的定義。

注冊 Bean 的處理器

AbstractApplicationContext#registerBeanPostProcessors

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
   PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

//PostProcessorRegistrationDelegate.java
public static void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
   // 獲取所有實現了BeanPostProcessor的beanName
   // 這里會獲取到AutowiredAnnotationProcessor和CommonAnnotationProcessor后置處理器的beanName
   String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);

   // 已經注冊進beanFactory的數量 + 手動注冊的BeanPostProcessorChecker + 實現了BeanPostProcessor還未注冊的bean的數量
   int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
   beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

   // 存儲實現了PriorityOrdered接口的BeanPostProcessors
   List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
   // 存儲實現了MergedBeanDefinitionPostProcessor接口的BeanPostProcessors
   List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
   // 存儲實現了Ordered接口的BeanPostProcessors
   List<String> orderedPostProcessorNames = new ArrayList<>();
   // 存儲正常的BeanPostProcessors
   List<String> nonOrderedPostProcessorNames = new ArrayList<>();

   for (String ppName : postProcessorNames) {
       // 如果實現了BeanPostProcessor的bean實現了PriorityOrdered接口
       if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
           // 獲取bean實例
           BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
           // 添加進priorityOrderedPostProcessors
           priorityOrderedPostProcessors.add(pp);
           // 如果bean也實現了MergedBeanDefinitionPostProcessor,則添加進internalPostProcessors
           if (pp instanceof MergedBeanDefinitionPostProcessor) {
               internalPostProcessors.add(pp);
           }
       }
       // 如果實現了Ordered接口,添加進orderedPostProcessorNames
       else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
           orderedPostProcessorNames.add(ppName);
       }
       // 否則添加進nonOrderedPostProcessorNames
       else {
           nonOrderedPostProcessorNames.add(ppName);
       }
   }

   // 將實現了PriorityOrdered的BeanPostProcessors先排序再注冊進beanFactory
   sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

   // 將實現了Order的BeanPostProcessors先排序再注冊進beanFactory
   List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
   for (String ppName : orderedPostProcessorNames) {
       BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
       orderedPostProcessors.add(pp);
       // 如果實現了MergedBeanDefinitionPostProcessor
       if (pp instanceof MergedBeanDefinitionPostProcessor) {
           // 添加進internalPostProcessors
           internalPostProcessors.add(pp);
       }
   }
   sortPostProcessors(orderedPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, orderedPostProcessors);

   // 將正常的BeanPostProcessors注冊進beanFactory
   List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
   for (String ppName : nonOrderedPostProcessorNames) {
       BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
       nonOrderedPostProcessors.add(pp);
       if (pp instanceof MergedBeanDefinitionPostProcessor) {
           internalPostProcessors.add(pp);
       }
   }
   registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

   // 最后將實現MergedBeanDefinitionPostProcessor的BeanPostProcessors先排序再注冊進beanFactory
   sortPostProcessors(internalPostProcessors, beanFactory);
   registerBeanPostProcessors(beanFactory, internalPostProcessors);

   // 這里再次添加了ApplicationListenerDetector(之前在prepareBeanFactory()已經添加過)是為了獲取代理
   beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

上面代碼最后的部分會把實現了 MergedBeanDefinitionPostProcessor 會在最后重新注冊一遍,大家可能會認為這不就重復注冊了嗎,其實不然,beanFactory#addBeanPostProcessor() 會首先刪除老的,再重新添加新的。

根據上面代碼大家也會發現,ApplicationContext 會幫我們自動注冊實現了 BeanPostProcessorsbean,而使用 BeanFactory 就需要自己手動注冊了。

注意:上面只是注冊,真正調用是在 getBean() 的時候。

初始化非懶加載的單例 bean

AbstractApplicationContext#finishBeanFactoryInitialization

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));
    }

    if (!beanFactory.hasEmbeddedValueResolver()) {
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    beanFactory.setTempClassLoader(null);

    // 凍結所有的bean定義,也就是bean定義將不被修改或任何進一步的處理
    beanFactory.freezeConfiguration();

    // 初始化非延遲的單例bean,見下文詳解
    beanFactory.preInstantiateSingletons();
}

DefaultListableBeanFactory#preInstantiateSingletons

public void preInstantiateSingletons() throws BeansException {
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    for (String beanName : beanNames) {
        // 獲取合并的BeanDefinition
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // bean不是抽象類 && bean是單例作用域 && bean不是延遲加載
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            // 如果bean的FactoryBean
            if (isFactoryBean(beanName)) {
                // 獲取FactoryBean的實例,前面加了&符號
                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 {
                        // FactoryBean是否提前初始化
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                       ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    // 如果是提前初始化直接調用getBean()去初始化bean
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            }
            // 直接調用getBean()去初始化bean
            else {
                getBean(beanName);
            }
        }
    }

    for (String beanName : beanNames) {
        // 獲取上面初始化后的單例bean
        Object singletonInstance = getSingleton(beanName);
        // 如果bean實現了SmartInitializingSingleton接口,調用afterSingletonsInstantiated()
        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();
            }
        }
    }
}

上面代碼中的 getMergedLocalBeanDefinition()Spring IoC bean 的創建有解析過,這里不再贅述。這里介紹一下 SmartInitializingSingleton 接口,先看下該接口的定義:

public interface SmartInitializingSingleton {

	/**
	 * 單例bean初始化完成之后調用
	 */
	void afterSingletonsInstantiated();

}

這個接口比較簡單,就一個方法,并且只在 preInstantiateSingletons() 中調用了,也就是說你直接使用 BeanFactory 是不會調用該回調方法的。該接口回調方法在單例 bean 初始化完成之后調用后執行,屬于 Spring Bean 生命周期的增強。

完成刷新

AbstractApplicationContext#finishRefresh

protected void finishRefresh() {
    // 清除資源緩存
    clearResourceCaches();
		
    // 為此上下文初始化生命周期處理器,見下文詳解
    initLifecycleProcessor();
		
    // 首先將刷新完畢事件傳播到生命周期處理器,見下詳解
    getLifecycleProcessor().onRefresh();

    // 發布上下文刷新完成的事件
    publishEvent(new ContextRefreshedEvent(this));

    LiveBeansView.registerApplicationContext(this);
}

AbstractApplicationContext#initLifecycleProcessor

protected void initLifecycleProcessor() {
    // 如果當前beanFactory中含有名稱為lifecycleProcessor的bean定義,初始化該bean并賦值給全局變量lifecycleProcessor
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
        this.lifecycleProcessor = beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
    } else {
        // beanFactory中沒有名稱為lifecycleProcessor的bean定義,創建一個DefaultLifecycleProcessor并當做單例bean注冊進beanFactory
        DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
        defaultProcessor.setBeanFactory(beanFactory);
        this.lifecycleProcessor = defaultProcessor;
        beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
    }
}

DefaultLifecycleProcessor#onRefresh

public void onRefresh() {
    startBeans(true);
    this.running = true;
}

private void startBeans(boolean autoStartupOnly) {
    // 獲取所有實現了Lifecycle或者SmartLifecycle的單例bean
    Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
    Map<Integer, LifecycleGroup> phases = new HashMap<>();
    // 因為onRefresh()調用時該方法時,手動設置了autoStartupOnly為false,所以這里的bean必需是SmartLifecycle類型并且isAutoStartup()返回true
    lifecycleBeans.forEach((beanName, bean) -> {
        if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
            // 獲取bean的階段值(如果沒有實現Phased接口,則值為0)
            int phase = getPhase(bean);
            // 拿到存放該階段值的LifecycleGroup,如果為空則新建一個并把當前階段值加入其中
            LifecycleGroup group = phases.get(phase);
            if (group == null) {
                group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
                phases.put(phase, group);
            }
            group.add(beanName, bean);
        }
    });
    // 如果phases不為空,根據階段值從小到大排序,并調用重寫Lifecycle接口的start()
    if (!phases.isEmpty()) {
        List<Integer> keys = new ArrayList<>(phases.keySet());
        Collections.sort(keys);
        for (Integer key : keys) {
            phases.get(key).start();
        }
    }
}

總結

本文主要介紹了 ApplicationContext 整個加載的流程,我們可以重新整理一下思路:

  1. 刷新前的準備,在這里會記錄整個上下文啟動的開始時間,將激活標識設置為 true,關閉標識設置為 false
  2. 創建一個新的 BeanFactory,這里大多數情況下都是 DefaultListableBeanFactory。首先會檢測之前有沒有 BeanFactory,有的話會先銷毀再重新創建,然后會加載 bean 的定義元信息。
  3. 配置 BeanFactory,設置 BeanFactoryclassLoader、表達式語言處理器、添加了 ApplicationContext 新增加的 Aware 接口回調等。
  4. 調用 BeanFactory 的后置處理器,這也是 BeanFactory 的擴展點;上文有分析過這里不再贅述。
  5. 注冊容器內所有的 BeanPostProcessors,上文也分析過,不再贅述;值得注意的是如果單單使用 BeanFactory 的話是不會自動注冊的。
  6. 初始化消息資源,這里沒有過多分析,因為對我們整個流程幾乎沒什么影響。
  7. 初始化事件傳播器。關于 Spring 的事件,我打算后面單獨寫一篇文章來介紹,這里就沒有多說。
  8. 在特殊的上下文環境中初始化指定的bean,模板方法留給子類實現。
  9. 注冊監聽器,這也留著到 Spring 事件中一起介紹。
  10. 初始化所有非延遲加載的單例 bean,并且會回調實現了 SmartInitializingSingleton 接口的 afterSingletonsInstantiated(),這個接口算是 bean 生命周期的增強。
  11. 完成上下文的刷新,調用生命周期處理器的 onRefresh() 并且發布上下文刷新完成事件。

最后,我模仿 Spring 寫了一個精簡版,代碼會持續更新。地址:https://github.com/leisurexi/tiny-spring

posted @ 2020-07-06 22:25  leisurexi  閱讀(...)  評論(...編輯  收藏
色网站直播