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  阅读(386)  评论(0编辑  收藏  举报