Spring IoC 容器的擴展

前言

本篇文章主要介紹 Spring 中 BeanFactory 的擴展 ApplicationContext,我們平時日常開發中也基本上是使用它,不會去直接使用 BeanFactory

那麼在 Spring 中 BeanFactoryApplicationContext 有什麼區別呢?

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

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

正文

首先來看一段使用 ApplicationContext 的簡單代碼,然後我們逐漸往下分析。

XML配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="//www.springframework.org/schema/beans"
	   xmlns:xsi="//www.w3.org/2001/XMLSchema-instance"
	   xmlns:context="//www.springframework.org/schema/context"
	   xsi:schemaLocation="//www.springframework.org/schema/beans //www.springframework.org/schema/beans/spring-beans.xsd //www.springframework.org/schema/context //www.springframework.org/schema/context/spring-context.xsd">
	
    <context:component-scan base-package="com.leisurexi.ioc.context" />

    <bean id="user" class="com.leisurexi.ioc.context.domain.User">
        <property name="id" value="1"/>
        <property name="name" value="leisurexi"/>
    </bean>

    <bean id="city" class="com.leisurexi.ioc.context.domain.City">
        <property name="id" value="1"/>
        <property name="name" value="北京"/>
    </bean>

</beans>

User 類定義如下:

public class User {

    private Long id;
    private String name;

    @Autowired
    private City city;

    // 省略get和set方法
}

測試類,如下:

@Test
public void xmlApplicationContextTest() {
    ApplicationContext context = new ClassPathXmlApplicationContext("application-context.xml");
    User user = context.getBean("user", User.class);
    System.out.println(user);
}

上面代碼很簡單,根據指定的文件加載 bean 定義,在調用 getBean() 獲取 bean 實例。下面我們從上面代碼開始一步一步分析 ApplicationContext 相比 BeanFactory 做了什麼其它工作。

ClassPathXmlApplicationContext 構造函數

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
    this(new String[] {configLocation}, true, null);
}

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
    super(parent);
    // 設置 XML 文件的路徑
    setConfigLocations(configLocations);
    if (refresh) {
        // 刷新上下文
        refresh();
    }
}

AbstractApplicationContext#refresh

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

        // Tell the subclass to refresh the internal bean factory.
        // 獲取刷新後的beanFactory,一般都是創建一個DefaultListableBeanFactory,見下文詳解
        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.
            // beanFactory的後置處理,子類實現,這也算是beanFactory的擴展點
            // AbstractRefreshableWebApplicationContext在這個方法內加入了request和session的作用域
            postProcessBeanFactory(beanFactory);

            // Invoke factory processors registered as beans in the context.
            // 調用所有BeanFactoryPostProcessors的實現類,見下文詳解
            invokeBeanFactoryPostProcessors(beanFactory);

            // Register bean processors that intercept bean creation.
            // 註冊BeanPostProcessors,見下文詳解
            registerBeanPostProcessors(beanFactory);

            // Initialize message source for this context.
            // 初始化消息資源,這裡不做過多分析
            initMessageSource();

            // Initialize event multicaster for this context.
            // 初始化事件傳播器,這裡不做過多分析
            initApplicationEventMulticaster();

            // Initialize other special beans in specific context subclasses.
            // 在特殊的上下文環境中初始化指定的bean,模板方法留給子類實現
            onRefresh();

            // Check for listener beans and register them.
            // 註冊監聽器
            registerListeners();

            // Instantiate all remaining (non-lazy-init) singletons.
            // 實例化所有非延遲加載的單例bean,見下文詳解
            finishBeanFactoryInitialization(beanFactory);

            // Last step: publish corresponding event.
            // 完成上下文的刷新,調用生命周期處理器的onRefresh()並且發佈上下文刷新完成事件
            finishRefresh();
        } catch (BeansException ex) {
            if (logger.isWarnEnabled()) {
                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;
        } finally {
            // Reset common introspection caches in Spring's core, since we
            // might not ever need metadata for singleton beans anymore...
            // 重置緩存,例如方法、字段等
            resetCommonCaches();
        }
    }
}

AbstractApplicationContext#prepareRefresh

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

    // Initialize any placeholder property sources in the context environment.
    // 初始化佔位符屬性資源,該方法是留給子類實現的,默認什麼也不做
    initPropertySources();

    // Validate that all properties marked as required are resolvable:
    // see ConfigurablePropertyResolver#setRequiredProperties
    // 驗證需要的屬性文件是否都已經放入環境中
    getEnvironment().validateRequiredProperties();

    // Store pre-refresh ApplicationListeners...
    if (this.earlyApplicationListeners == null) {
        this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
    } else {
        // Reset local application listeners to pre-refresh state.
        // 在上下文刷新前重置監聽器
        this.applicationListeners.clear();
        this.applicationListeners.addAll(this.earlyApplicationListeners);
    }

    // Allow for the collection of early ApplicationEvents,
    // to be published once the multicaster is available...
    this.earlyApplicationEvents = new LinkedHashSet<>();
}

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;
        }
    }
    catch (IOException ex) {
        throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
    }
}

上面代碼中的 destroyBeans() 最終會調用 DefaultListableBeanFactory#destroySingletons() ,該方法在 Spring IoC createBean 方法詳解 一文中已經介紹過,這裡不再贅述。

loadBeanDefinitions() 方法最終會創建 XmlBeanDefinitionReader#loadBeanDefinitions() 去加載 bean 的定義元信息,該方法在 Spring XML Bean 定義的加載和註冊 一文中已經介紹過,這裡不再贅述;其中對 context:componment-scan 標籤的解析在 Spring IoC component-scan 節點詳解 一文中介紹過,這裡也不再贅述。

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

AbstractApplicationContext#prepareBeanFactory

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

    // Configure the bean factory with context callbacks.
    // 添加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);

    // BeanFactory interface not registered as resolvable type in a plain factory.
    // MessageSource registered (and found for autowiring) as a bean.
    // 註冊解決依賴,也就是說我們可以通過依賴注入來注入以下四種類型的bean
    beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
    beanFactory.registerResolvableDependency(ResourceLoader.class, this);
    beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
    beanFactory.registerResolvableDependency(ApplicationContext.class, this);

    // Register early post-processor for detecting inner beans as ApplicationListeners.
    // 將是ApplicationListener類型的bean在BeanPostProcessor的初始化後回調方法中加入到context的監聽器列表中
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // Detect a LoadTimeWeaver and prepare for weaving, if found.
    // 增加對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()));
    }

    // Register default environment beans.
    // 如果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());
    }
}

AbstractApplicationContext#invokeBeanFactoryPostProcessors

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
    // 實例化並調用所有已註冊的BeanFactoryPostProcessor
    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()));
    }
}

PostProcessorRegistryDelegate#invokeBeanFactoryPostProcessors

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

    // Invoke BeanDefinitionRegistryPostProcessors first, if any.
    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);
            }
        }

        // Do not initialize FactoryBeans here: We need to leave all regular beans
        // uninitialized to let the bean factory post-processors apply to them!
        // Separate between BeanDefinitionRegistryPostProcessors that implement
        // PriorityOrdered, Ordered, and the rest.
        List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

        // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
        // 獲取所有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();

        // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
        // 和上面的差不多只是這次是實現了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();

        // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
        // 和上面的差不多只是這次是所有的實現了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();
        }

        // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
        // 調用BeanFactoryPostProcessor的postProcessBeanFactory()
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }

    else {
        // Invoke factory processors registered with the context instance.
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }

    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let the bean factory post-processors apply to them!
    // 獲取所有BeanFactoryPostProcessor類型的beanName
    String[] postProcessorNames =
        beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

    // Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    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)) {
            // skip - already processed in first phase above
        }
        // 如果實現了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);
        }
    }

    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    // 排序,然後調用BeanFactoryPostProcessors的postProcessBeanFactory()
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    // 和上面的一樣這裡是實現了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);

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

    // Clear cached merged bean definitions since the post-processors might have
    // modified the original metadata, e.g. replacing placeholders in values...
    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 {

    /**
     * 實例化bean之前調用,可以在此註冊bean或刪除bean
     */
    void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

BeanDefinitionRegistryPostProcessorBeanFactoryPostProcessor 具有更高的優先級,從上面解析的代碼中就可以看出,主要用來在 BeanFactoryPostProcessor 之前註冊其它 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);

    // Register BeanPostProcessorChecker that logs an info message when
    // a bean is created during BeanPostProcessor instantiation, i.e. when
    // a bean is not eligible for getting processed by all BeanPostProcessors.
    // 已經註冊進beanFactory的數量 + 手動註冊的BeanPostProcessorChecker + 實現了BeanPostProcessor還未註冊的bean的數量
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    // 存儲實現了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);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    // 將實現了PriorityOrdered的BeanPostProcessors先排序再註冊進beanFactory
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    // 將實現了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);

    // Now, register all regular BeanPostProcessors.
    // 將正常的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);

    // Finally, re-register all internal BeanPostProcessors.
    // 最後將實現MergedBeanDefinitionPostProcessor的BeanPostProcessors先排序再註冊進beanFactory
    sortPostProcessors(internalPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, internalPostProcessors);

    // Re-register post-processor for detecting inner beans as ApplicationListeners,
    // moving it to the end of the processor chain (for picking up proxies etc).
    // 這裡再次添加了ApplicationListenerDetector(之前在prepareBeanFactory()已經添加過)是為了獲取代理
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

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

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

AbstractApplicationContext#finishBeanFactoryInitialization

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // Initialize conversion service for this context.
    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));
    }

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    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);
    }

    // Stop using the temporary ClassLoader for type matching.
    beanFactory.setTempClassLoader(null);

    // Allow for caching all bean definition metadata, not expecting further changes.
    // 凍結所有的bean定義,也就是bean定義將不被修改或任何進一步的處理
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    // 初始化非延遲的單例bean,見下文詳解
    beanFactory.preInstantiateSingletons();
}

DefaultListableBeanFactory#preInstantiateSingletons

public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
        logger.trace("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<>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    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);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    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 getBean 方法詳解](//leisurexi.github.io/category/2020/04/21/Spring IoC/Spring IoC getBean 方法詳解.html)有解析過,這裡不再贅述。這裡介紹一下 SmartInitializingSingleton 接口,先看下該接口的定義:

public interface SmartInitializingSingleton {

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

}

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

AbstractApplicationContext#finishRefresh

protected void finishRefresh() {
    // Clear context-level resource caches (such as ASM metadata from scanning).
    // 清除資源緩存
    clearResourceCaches();
		
    // Initialize lifecycle processor for this context.
    // 為此上下文初始化生命周期處理器,見下文詳解
    initLifecycleProcessor();
		
    // Propagate refresh to lifecycle processor first.
    // 首先將刷新完畢事件傳播到生命周期處理器,見下詳解
    getLifecycleProcessor().onRefresh();

    // Publish the final event.
    // 發佈上下文刷新完成的事件
    publishEvent(new ContextRefreshedEvent(this));

    // Participate in LiveBeansView MBean, if active.
    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 寫了一個精簡版,代碼會持續更新。地址://github.com/leisurexi/tiny-spring。訪問新博客地址,觀看效果更佳 //leisurexi.github.io/