Spring IOC 源码解析之refresh(二)

Spring5.1.x版本,使用注解扫描的方式

接上一篇Spring IOC 源码解析之创建应用上下文(一),继续来分析refresh方法。

public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        // 准备工作,比如记录容器启动时间等(不重要)
        prepareRefresh();

        // Tell the subclass to refresh the internal bean factory.
        // 初始化bean工厂
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // Prepare the bean factory for use in this context.
        // 设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean
        prepareBeanFactory(beanFactory);

        try {
            // Allows post-processing of the bean factory in context subclasses.
            // 【这里需要知道 BeanFactoryPostProcessor 这个知识点,Bean 如果实现了此接口,
            // 那么在容器初始化以后,Spring 会负责调用里面的 postProcessBeanFactory 方法。
            // 实现该接口,可以在bean实例化之前获取beanFactory并可以修改bean定义属性】

            // 这里是提供给子类的扩展点,到这里的时候,所有的 Bean 都加载、注册完成了,但是都还没有初始化
            // 具体的子类可以在这步的时候添加一些特殊的 BeanFactoryPostProcessor 的实现类或做点什么事
            postProcessBeanFactory(beanFactory);

            // Invoke factory processors registered as beans in the context.
            // 调用 BeanFactoryPostProcessor 各个实现类的 postProcessBeanFactory(factory) 方法
            // 采用注解方式时,在这里,会扫描注解将类解析成bean定义放到map中
            invokeBeanFactoryPostProcessors(beanFactory);

            // 注册bean后置处理器
            registerBeanPostProcessors(beanFactory);

            // 国际化相关
            initMessageSource();

            // 事件监听广播器
            initApplicationEventMulticaster();

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

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

            // Instantiate all remaining (non-lazy-init) singletons.
            // 开始初始化单例bean(没有设置懒加载)
            finishBeanFactoryInitialization(beanFactory);

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

        catch (BeansException ex) {
            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();
        }
    }
}

这里面主要有12个方法,接下来一个一个来分析。

prepareRefresh

第一步主要是做一些准备工作,比如记录容器启动时间等

protected void prepareRefresh() {
    // 开始时间
    this.startupDate = System.currentTimeMillis();
    this.closed.set(false);
    this.active.set(true);

    if (logger.isDebugEnabled()) {
        if (logger.isTraceEnabled()) {
            logger.trace("Refreshing " + this);
        }
        else {
            logger.debug("Refreshing " + getDisplayName());
        }
    }

    // 初始化属性源,默认没有做事情,由子类重写
    initPropertySources();

    // Validate that all properties marked as required are resolvable:
    // see ConfigurablePropertyResolver#setRequiredProperties
    // 校验必需的属性是否有配置,通过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<>();
}

obtainFreshBeanFactory

初始化bean工厂

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
    // 由于采用注解方式时,在此之前已经创建好了容器,所以这里什么都不做
    refreshBeanFactory();
    // 返回内部的BeanFactory
    return getBeanFactory();
}

public final ConfigurableListableBeanFactory getBeanFactory() {
    return this.beanFactory;
}

prepareBeanFactory

这步用来设置 BeanFactory 的类加载器,添加几个 BeanPostProcessor,手动注册几个特殊的 bean。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
    // 设置类加载器
    beanFactory.setBeanClassLoader(getClassLoader());
    // 添加一个bean表达式解析器
    beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    // 添加属性编辑器
    beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

    // 添加一个bean后置处理器,这个Processor的作用在于为实现下面几个*Aware接口的bean调用该Aware接口定义的方法,
    // 并传入对应的参数。比如实现EnvironmentAware接口的bean在该Processor内会调用EnvironmentAware接口的setEnvironment方法,
    // 并把spring容器内部的ConfigurableEnvironment传递进去
    beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
    // 忽略下面几个接口实现类中存在依赖外部的bean属性注入,因为这几个类是由上面的ApplicationContextAwareProcessor后置处理器通过setter来设置的
    // (这个是对在xml中使用默认自动装配default-autowire/autowire属性才生效,使用@Autowire注解是不起作用的,实际应用中很少使用)
    // 比如下面这个EnvironmentAware,使得我们的EnvironmentAware接口实现类在自动装配时不能自动注入Environment对象的依赖,
    // 而统一由框架来设置,就是在ApplicationContextAwareProcesso中完成的
    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时,如果要注入该类型接口的对象时,会注入该方法指定的对象,而不去管其它接口实现类
    // 类似于我们自己开发时使用的@primary注解或@Qualifier注解,来具体指定注入哪个bean
    // 比如下面几个,当外部类要自动注入BeanFactory时,会注入当前的BeanFactory(DefaultListableBeanFactory),
    // 注入ResourceLoader,ApplicationEventPublisher,ApplicationContext时,会注入当前对象(比如AnnotationConfigApplicationContext)
    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.
    // 添加bean后置处理器,该后置处理器用于将实现了ApplicationListener接口的内部bean注册监听
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

    // 当容器中存在名称为loadTimeWeaver的bean时,注册一个LoadTimeWeaverAwareProcessor后置处理器
    // 如果bean实现了LoadTimeWeaverAware接口,该后置处理器会将loadTimeWeaver设置给该bean
    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()));
    }

    // 注册一些默认的系统环境的bean
    if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
    }
    if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
        beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
    }
}

postProcessBeanFactory

该方法在当前例子中没有实现,用在web环境中的,暂时先不解析了。

invokeBeanFactoryPostProcessors

看名称就知道这个方法是调用BeanFactory后置处理器的

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

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

public List<BeanFactoryPostProcessor> getBeanFactoryPostProcessors() {
    return this.beanFactoryPostProcessors;
}

getBeanFactoryPostProcessors是获取容器中BeanFactory后置处理器集合列表的,通过前面的分析,spring没有往后置处理器缓存中添加任何的BeanFactory后置处理器,虽然前面讲到实例化AnnotatedBeanDefinitionReader时添加了一个BeanFactory后置处理器ConfigurationClassPostProcessor,但它目前还只是一个普通的bean定义,并不在后置处理器缓存中,并且我们自定义的使用注解标注的BeanFactory后置处理器也还没有开始扫描到,所以该集合内还没有任何的后置处理器,通过debug也可以看出
在这里插入图片描述

所以这里调invokeBeanFactoryPostProcessors方法时传入的是一个空集合,除非在容器刷新前手动调用接口添加BeanFactory后置处理器进去

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

    // Invoke BeanDefinitionRegistryPostProcessors first, if any.
    // 因为下面会分多次循环调用,所以为了防止重复调用,
    // 定义一个集合用来保存已经调用过的BeanDefinitionRegistryPostProcessor名称
    Set<String> processedBeans = new HashSet<>();

    // DefaultListableBeanFactory实现了BeanDefinitionRegistry接口,所以会进入
    // 实现了BeanDefinitionRegistry接口,说明该bean工厂可以注册bean定义,
    // 所以需要去调BeanDefinitionRegistryPostProcessor接口方法注册自定义的bean定义
    if (beanFactory instanceof BeanDefinitionRegistry) {
        BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
        
        // 这里将BeanFactoryPostProcessor分成两部分,一部分是普通的BeanFactoryPostProcessor,只需调用postProcessBeanFactory方法,
        // 另一部分是实现了BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor,
        // 在调用postProcessBeanFactory方法之前,还需调用postProcessBeanDefinitionRegistry方法,所以分成两部分来调用
        
        // 普通的BeanFactoryPostProcessor
        List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
        // 实现了BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor
        List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

        // 目前这里是空的,所以会跳过
        for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
            // 如果该后置处理器实现了BeanDefinitionRegistryPostProcessor接口,则调用它的postProcessBeanDefinitionRegistry方法,
            // 修改注册表中的bean定义,
            // 并将该后置处理器添加到registryProcessors中,
            // 否则作为普通的后置处理器添加到regularPostProcessors中
            if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
                BeanDefinitionRegistryPostProcessor registryProcessor =
                    (BeanDefinitionRegistryPostProcessor) postProcessor;
                registryProcessor.postProcessBeanDefinitionRegistry(registry);
                registryProcessors.add(registryProcessor);
            }
            else {
                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<>();

        // 1、=============================================================================
        // First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
        // 首先调用实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessors
        
        // 从bean定义缓存中获取BeanDefinitionRegistryPostProcessor类型的bean名称数组
        // 这里会获取到一开始添加的ConfigurationClassPostProcessor bean定义
        // 该类实现了BeanDefinitionRegistryPostProcessor接口,可以实现动态的添加bean定义
        String[] postProcessorNames =
            beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
        for (String ppName : postProcessorNames) {
            // 这里会通过getBean来获取ConfigurationClassPostProcessor,
            // 如果还不存在就创建,因为需要该处理器来扫描注解,所以需要提前创建
            if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
                currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
                // 将实现PriorityOrdered的postProcessor名称暂存到processedBeans集合中
                // 防止后面重复调用
                processedBeans.add(ppName);
            }
        }
        // 排序
        sortPostProcessors(currentRegistryProcessors, beanFactory);
        // 合并集合
        registryProcessors.addAll(currentRegistryProcessors);
        // 分别调用每个BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法,
        // 该方法可以动态的修改beanFactory中的bean定义
        // 这个例子中该集合只有一个ConfigurationClassPostProcessor
        // 这一步是一个关键步骤,因为ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法
        // 会进行注解扫描,处理@Configuration/@Component等注解,扫描、注册包下的类
        // 处理@Import/@ImportResource/@Bean等
        // 下面再从bean定义注册表获取就会获取到扫描到的bean定义
        invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
        // 调完后清空该集合
        currentRegistryProcessors.clear();
        
        // 2、=============================================================================

        // Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
        // 接着调用实现了Ordered接口的BeanDefinitionRegistryPostProcessors
        
        // 照样也是从bean定义缓存中获取,但这里可能会获取到注解扫描到的bean
        // 然后创建bean,调用postProcessBeanDefinitionRegistry方法
        // 虽然ConfigurationClassPostProcessor也实现了Ordered接口,但是由于前面已经调用过了postProcessBeanDefinitionRegistry方法
        // 所以这里不会再重复调用该方法。
        // 这里可能会调到注解标注的自定义后置器,因为上面已经扫描过了,注册成了bean定义
        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();

        // 3、=======================================================================
        
        // Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
        // 最后调用其它的BeanDefinitionRegistryPostProcessors(没有实现PriorityOrdered和Ordered接口),
        // 包括自定义的用注解标注的,但是只调BeanDefinitionRegistryPostProcessor里的方法
        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);
                    // 重新设置为true,表示要再循环一次,
                    // 因为其它的BeanDefinitionRegistryPostProcessors可能也会注册一个新的
                    // BeanDefinitionRegistryPostProcessor bean定义,
                    // 所以需要重新循环一次来执行可能新添加的BeanDefinitionRegistryPostProcessor
                    reiterate = true;
                }
            }
            sortPostProcessors(currentRegistryProcessors, beanFactory);
            registryProcessors.addAll(currentRegistryProcessors);
            invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
            currentRegistryProcessors.clear();
        }
		// 4、========================================================================
        
        // Now, invoke the postProcessBeanFactory callback of all processors handled so far.
        // 现在,才要开始调用postProcessBeanFactory的方法postProcessBeanFactory,
        // 前面调用的都是子接口BeanDefinitionRegistryPostProcessor的方法
        // 注意,这里不会调到自定义用注解标注的普通BeanFactoryPostProcessor,
        // 因为regularPostProcessors集合是从入参beanFactoryPostProcessors中分离出来的
        // 但如果实现了BeanDefinitionRegistryPostProcessor, PriorityOrdered/Ordered,
        // 则会在这里调用到,因为在registryProcessors里
        // 说实话有点绕
        invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
        invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
    }

    else {
        // Invoke factory processors registered with the context instance.
        // 该bean工厂没有提供bean定义注册功能,所以直接去调BeanFactoryPostProcessor
        // 接口方法就行了
        // 照样这里也还没调到注解标注的后置器
        invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
    }

    // 5、========================================================================
    
    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let the bean factory post-processors apply to them!
    // 从bean定义缓存中获取所有的BeanFactoryPostProcessor实现类
    // 然后有分成几部分分别调用
    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<>();
    for (String ppName : postProcessorNames) {
        if (processedBeans.contains(ppName)) {
            // 跳过,已经在上面的步骤调过了
        }
        else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
        }
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

    // Next, invoke the BeanFactoryPostProcessors that implement Ordered.
    List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
    for (String postProcessorName : orderedPostProcessorNames) {
        orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

    // Finally, invoke all other BeanFactoryPostProcessors.
    List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    for (String postProcessorName : nonOrderedPostProcessorNames) {
        nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
    }
    invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
    // 到这里所有的BeanFactory后置器都调用完了

    // Clear cached merged bean definitions since the post-processors might have
    // modified the original metadata, e.g. replacing placeholders in values...
    beanFactory.clearMetadataCache();
}

在调用BeanFactoryPostProcessor接口方法之前,会先调用它的继承接口BeanDefinitionRegistryPostProcessor接口的方法postProcessBeanDefinitionRegistry。BeanDefinitionRegistryPostProcessor是对BeanFactoryPostProcessor接口的扩展,允许在常规 BeanFactoryPostProcessor 开始调用之前进一步注册一些 bean 定义。特别是,BeanDefinitionRegistryPostProcessor 可以进一步注册 BeanFactoryPostProcessor 的bean定义实例。在Spring中,BeanDefinitionRegistryPostProcessor 的实现类只有一个,就是ConfigurationClassPostProcessor。该类用来处理@Configuration/@Component等注解,扫描、注册包下的类处理@Import/@ImportResource/@Bean等,具体可以看ConfigurationClassPostProcessor解析那篇。

该方法结束后,所有类都解析成bean定义了,但还没实例化。

registerBeanPostProcessors

看方法名就知道是注册bean后置处理器了,实例化并注册所有 BeanPostProcessor bean,由于该后置处理器是作用于bean的,所以要先于其它bean进行实例化

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

PostProcessorRegistrationDelegate

public static void registerBeanPostProcessors(
    	ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

    // 获取所有BeanPostProcessor类型的bean定义名称
    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.
    // 计算bean后置处理器个数,缓存中现有的BeanPostProcessor(通过beanFactory.addBeanPostProcessor(bpp)添加进容器的)
    // +bean定义中还没实例化的
    int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
    // 添加一个bean后置处理器
    beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

    // Separate between BeanPostProcessors that implement PriorityOrdered,
    // Ordered, and the rest.
    // 因为要排序,所以将实现了PriorityOrdered,Ordered和其它的BeanPostProcessors分开
    List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
    List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
    List<String> orderedPostProcessorNames = new ArrayList<>();
    List<String> nonOrderedPostProcessorNames = new ArrayList<>();
    for (String ppName : postProcessorNames) {
        // 如果实现了PriorityOrdered接口,就调用getBean方法,相当于实例化,并将实例
        // 放置priorityOrderedPostProcessors集合中
        if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
            BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
            priorityOrderedPostProcessors.add(pp);
            // 如果也实现了MergedBeanDefinitionPostProcessor接口,也放置进internalPostProcessors中
            if (pp instanceof MergedBeanDefinitionPostProcessor) {
                internalPostProcessors.add(pp);
            }
        }
        // 如果实现了Ordered接口,将bean名称放入orderedPostProcessorNames集合中,
        // 这里没有进行实例化
        else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
            orderedPostProcessorNames.add(ppName);
        }
        // 否则放入nonOrderedPostProcessorNames
        else {
            nonOrderedPostProcessorNames.add(ppName);
        }
    }

    // First, register the BeanPostProcessors that implement PriorityOrdered.
    // 1、首先对实现了PriorityOrdered接口的排序,然后注册进BeanPostProcessors
    sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

    // Next, register the BeanPostProcessors that implement Ordered.
    // 2、接着对实现了Ordered接口的进行实例化,排序,注册进BeanPostProcessors
    // 如果也实现了MergedBeanDefinitionPostProcessor接口,也放置进internalPostProcessors中
    List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
    for (String ppName : orderedPostProcessorNames) {
        BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
        orderedPostProcessors.add(pp);
        if (pp instanceof MergedBeanDefinitionPostProcessor) {
            internalPostProcessors.add(pp);
        }
    }
    sortPostProcessors(orderedPostProcessors, beanFactory);
    registerBeanPostProcessors(beanFactory, orderedPostProcessors);

    // Now, register all regular BeanPostProcessors.
    // 然后,注册其它普通的BeanPostProcessors,
    // 照样也是实现了MergedBeanDefinitionPostProcessor接口,就放置进internalPostProcessors中
    List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
    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接口的全部排序一遍重新注册
    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
    // 主要是将该后置器放到调用链的最后
    beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}

在这之前,spring默认会添加3个bean后置处理器实例
image.png
ApplicationContextAwareProcessor和ApplicationListenerDetector是在prepareBenFactory方法中添加的,而ImportAwareBeanPostProcessor是在invokeBeanFactoryPostProcessors方法中调用ConfigurationClassPostProcessor类的postProcessBeanFactory方法时添加的
image.png
然后也默认注册了两个BeanPostProcessor bean定义
image.png
是在实例化AnnotationConfigApplicationContext时添加的
image.png
至于最后为啥将实现了MergedBeanDefinitionPostProcessor接口的全部排序一遍重新注册,重新注册无非就是将后置处理器移到缓存的最后面。

initMessageSource

这个是做国际化配置的,可以不关注

protected void initMessageSource() {
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    // 判断容器中是否有MessageSource,没有的话会创建DelegatingMessageSource注册成单例
    if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
        this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
        // Make MessageSource aware of parent MessageSource.
        if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
            HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
            if (hms.getParentMessageSource() == null) {
                // Only set parent context as parent MessageSource if no parent MessageSource
                // registered already.
                hms.setParentMessageSource(getInternalParentMessageSource());
            }
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Using MessageSource [" + this.messageSource + "]");
        }
    }
    else {
        // Use empty MessageSource to be able to accept getMessage calls.
        DelegatingMessageSource dms = new DelegatingMessageSource();
        dms.setParentMessageSource(getInternalParentMessageSource());
        this.messageSource = dms;
        beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
        }
    }
}

initApplicationEventMulticaster

内容也很简单,就是创建事件监听广播器,用来发布事件用的

protected void initApplicationEventMulticaster() {
    // 判断容器中是否有ApplicationEventMulticaster,
    // 没有的话创建SimpleApplicationEventMulticaster注册成单例
    ConfigurableListableBeanFactory beanFactory = getBeanFactory();
    if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
        this.applicationEventMulticaster =
            beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
        if (logger.isTraceEnabled()) {
            logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
        }
    }
    else {
        this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
        beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
        if (logger.isTraceEnabled()) {
            logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
                         "[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
        }
    }
}

onRefresh

默认是空实现,交由子类重写
在这里插入图片描述
AnnotationConfigApplicationContext类没有重写。
springboot的自带的servlet容器就是在该方法内实现的。

registerListeners

注册监听器,将监听器注册进广播器,并发布早期事件

protected void registerListeners() {
    // Register statically specified listeners first.
    for (ApplicationListener<?> listener : getApplicationListeners()) {
        getApplicationEventMulticaster().addApplicationListener(listener);
    }

    // Do not initialize FactoryBeans here: We need to leave all regular beans
    // uninitialized to let post-processors apply to them!
    String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
    for (String listenerBeanName : listenerBeanNames) {
        getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
    }

    // Publish early application events now that we finally have a multicaster...
    Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
    this.earlyApplicationEvents = null;
    if (earlyEventsToProcess != null) {
        for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
            getApplicationEventMulticaster().multicastEvent(earlyEvent);
        }
    }
}

finishBeanFactoryInitialization

该方法是一个重要的方法,因为会在这里面实例化非懒加载的单例bean

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // Initialize conversion service for this context.
    // 首先初始化名字为 conversionService 的 Bean
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
        beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
        // getBean里有初始化逻辑
        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.
    // 初始化 LoadTimeWeaverAware 类型的 Bean
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

    // 停止使用临时的ClassLoader进行类型匹配
    beanFactory.setTempClassLoader(null);

    // 冻结所有 bean 定义,表示注册的 bean 定义将不会被修改或进一步处理
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    // 开始实例化剩余的非懒加载的单例bean
    beanFactory.preInstantiateSingletons();
}

直接看最后一个方法,进入DefaultListableBeanFactory

/**
 * 开始初始化单例
 */
@Override
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.
    // 1、复制一份beanDefinitionNames出来遍历,以允许init等方法注册新的bean定义
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {
        // 2、得到合并后的beanDefinition
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 初始化非抽象、单例、非懒加载的bean
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            // 3、判断是否是FactoryBean
            if (isFactoryBean(beanName)) {
                // 4、FactoryBean bean名称前加“&”符号,所以要获取FactoryBean实例,要加&前缀
                Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                if (bean instanceof FactoryBean) {
                    final FactoryBean<?> factory = (FactoryBean<?>) bean;
                    boolean isEagerInit;
                    // 判断该FactoryBean是否需要立即实例化它里面的bean
					// 单纯实现FactoryBean默认是会延迟实例化里面的bean,但实现SmartFactoryBean接口可以设置是否延迟
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
                                        ((SmartFactoryBean<?>) factory)::isEagerInit,
                                getAccessControlContext());
                    }
                    else {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    // 需要立马实例化
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            }
            else {
                // 5、实例化普通bean
                getBean(beanName);
            }
        }
    }

    // 6、到这里说明所有的非懒加载的 singleton beans 已经完成了初始化
	// 这里会对所哟实现了SmartInitializingSingleton接口的bean调用afterSingletonsInstantiated方法,
	// 这是spring提供的一个扩展点,在所有非懒加载单例bean都实例化后调用的
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        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();
            }
        }
    }
}

1、复制一份beanDefinitionNames出来遍历,以允许init等方法注册新的bean定义。
2、得到合并后的beanDefinition,这里有一个父子BeanDefinition的概念。

protected RootBeanDefinition getMergedLocalBeanDefinition(String beanName) throws BeansException {
    // 先看下缓存中是否已经有了
    RootBeanDefinition mbd = this.mergedBeanDefinitions.get(beanName);
    if (mbd != null) {
        return mbd;
    }
    // 获取合并后的BeanDefinition
    return getMergedBeanDefinition(beanName, getBeanDefinition(beanName));
}

protected RootBeanDefinition getMergedBeanDefinition(String beanName, BeanDefinition bd)
    	throws BeanDefinitionStoreException {

    return getMergedBeanDefinition(beanName, bd, null);
}

getBeanDefinition(beanName)就是从BeanDefinition缓存中获取。
如果给定 bean 定义是子bean定义,则通过与父合并返回给定bean的 RootBeanDefinition。

protected RootBeanDefinition getMergedBeanDefinition(
        String beanName, BeanDefinition bd, @Nullable BeanDefinition containingBd)
        throws BeanDefinitionStoreException {

    synchronized (this.mergedBeanDefinitions) {
        // 最终要返回的合并后的RootBeanDefinition
        RootBeanDefinition mbd = null;

        // 如果containingBd是空的则再检查一遍
        if (containingBd == null) {
            mbd = this.mergedBeanDefinitions.get(beanName);
        }

        if (mbd == null) {
            if (bd.getParentName() == null) {
                // 如果没有父bean定义,则不需要合并,则直接将自身copy出一个RootBeanDefinition
                // 或根据自身构建一个RootBeanDefinition
                if (bd instanceof RootBeanDefinition) {
                    mbd = ((RootBeanDefinition) bd).cloneBeanDefinition();
                }
                else {
                    mbd = new RootBeanDefinition(bd);
                }
            }
            else {
                // 子bean定义需要去合并父bean定义
                BeanDefinition pbd;
                try {
                    // 获取真正的名称(解析别名或去除前缀)
                    String parentBeanName = transformedBeanName(bd.getParentName());
                    if (!beanName.equals(parentBeanName)) {
                        // 如果父bean定义名称跟当前的名称不一样,
                        // 则获取父bean定义的合并BeanDefinition,
                        // 因为父bean可能自己也有父bean,即当前bean的爷爷bean
                        pbd = getMergedBeanDefinition(parentBeanName);
                    }
                    else {
                        // 如果父子名称相同,则必须通过父容器来获取父bean的合并bean定义,
                        // 并且父容器必须是ConfigurableBeanFactory类型,否则抛异常
                        BeanFactory parent = getParentBeanFactory();
                        if (parent instanceof ConfigurableBeanFactory) {
                            pbd = ((ConfigurableBeanFactory) parent).getMergedBeanDefinition(parentBeanName);
                        }
                        else {
                            throw new NoSuchBeanDefinitionException(parentBeanName,
                                                                    "Parent name '" + parentBeanName + "' is equal to bean name '" + beanName +
                                                                    "': cannot be resolved without an AbstractBeanFactory parent");
                        }
                    }
                }
                catch (NoSuchBeanDefinitionException ex) {
                    throw new BeanDefinitionStoreException(bd.getResourceDescription(), beanName,
                                                           "Could not resolve parent bean definition '" + bd.getParentName() + "'", ex);
                }
                // 使用父定义pbd构建一个新的RootBeanDefinition对象(深拷贝)
                mbd = new RootBeanDefinition(pbd);
                // 使用当前的bd覆盖
                mbd.overrideFrom(bd);
            }

            // Set default singleton scope, if not configured before.
            // 如果没有配置scope,则默认单例
            if (!StringUtils.hasLength(mbd.getScope())) {
                mbd.setScope(RootBeanDefinition.SCOPE_SINGLETON);
            }

            // A bean contained in a non-singleton bean cannot be a singleton itself.
            // Let's correct this on the fly here, since this might be the result of
            // parent-child merging for the outer bean, in which case the original inner bean
            // definition will not have inherited the merged outer bean's singleton status.
            // 如果containingBd不为空 && containingBd不为singleton && mbd为singleton,
            // 则将mdb的scope设置为containingBd的scope
            if (containingBd != null && !containingBd.isSingleton() && mbd.isSingleton()) {
                mbd.setScope(containingBd.getScope());
            }

            // Cache the merged bean definition for the time being
            // (it might still get re-merged later on in order to pick up metadata changes)
            // 将合并后的bean定义缓存起来
            if (containingBd == null && isCacheBeanMetadata()) {
                this.mergedBeanDefinitions.put(beanName, mbd);
            }
        }

        return mbd;
    }
}

3、判断是否是FactoryBean。

@Override
public boolean isFactoryBean(String name) throws NoSuchBeanDefinitionException {
    // 将别名和带前缀的名称转换为真正的名称
    String beanName = transformedBeanName(name);
    // 获取bean实例
    Object beanInstance = getSingleton(beanName, false);
    // 如果bean实例存在,则直接返回bean实例是否实现了FactoryBean接口
    if (beanInstance != null) {
        return (beanInstance instanceof FactoryBean);
    }
    // 如果没找到单例bean,则判断bean定义,如果也没找到,则取父容器判断
    if (!containsBeanDefinition(beanName) && getParentBeanFactory() instanceof ConfigurableBeanFactory) {
        // No bean definition found in this factory -> delegate to parent.
        return ((ConfigurableBeanFactory) getParentBeanFactory()).isFactoryBean(name);
    }
    // 判断beanName对应bean是否是FactoryBean类型
    return isFactoryBean(beanName, getMergedLocalBeanDefinition(beanName));
}

protected boolean isFactoryBean(String beanName, RootBeanDefinition mbd) {
    // 获取到beanName对应bean的类型
    Class<?> beanType = predictBeanType(beanName, mbd, FactoryBean.class);
    // 判断是否是FactoryBean类型
    return (beanType != null && FactoryBean.class.isAssignableFrom(beanType));
}

4、FactoryBean bean名称前加“&”符号,所以要获取FactoryBean实例,要加&前缀。
5、需要重点分析下getBean方法。

该方法留在下一篇Spring IOC 源码解析之getBean(三)再分析。

finishRefresh

这是刷新容器的最后一步

protected void finishRefresh() {
    // Clear context-level resource caches (such as ASM metadata from scanning).
    // 清除资源缓存
    clearResourceCaches();

    // 为上下文初始化生命周期处理器
    initLifecycleProcessor();

    // 首先将刷新传播到生命周期处理器
    getLifecycleProcessor().onRefresh();

    // 发布容器刷新完毕事件
    publishEvent(new ContextRefreshedEvent(this));

    // Participate in LiveBeansView MBean, if active.
    LiveBeansView.registerApplicationContext(this);
}

没什么可讲的,可以不用关注。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值