SpringBoot应用--02-AbstractApplicationContext#refresh方法解析

1.AbstractApplicationContext#refresh方法总览

    @Override
    public void refresh() throws BeansException, IllegalStateException {
        synchronized (this.startupShutdownMonitor) {
            /* Prepare this context for refreshing. -- 1. 准备当前需要refresh的上下文,设置其开始时间和活动标识同时处理好各种属性资源配置的初始化操作  */
            prepareRefresh();

            /* Tell the subclass to refresh the internal bean factory. -- 告诉子类刷新内部bean工厂 */
            ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

            /**
             * Prepare the bean factory for use in this context.
             * --配置工厂的标准上下文特征属性,例如类加载器,Bean处理器,事件发布器,运行环境,属性资源注册器,Bean表达式处理器等
             */
            prepareBeanFactory(beanFactory);

            try {
                /**
                 * Allows post-processing of the bean factory in context subclasses.
                 *  -- Register request/session scopes, a {@link ServletContextAwareProcessor}, etc.
                 *  -- 注册request|session|application 的作用域(相关依赖组件) + 添加一个ServletContextAwareProcessor处理器
                 *      + 注册环境中的Beans(servletContext  servletConfig contextParameters contextAttributes)
                 */
                postProcessBeanFactory(beanFactory);

                /**
                 * Invoke factory processors registered as beans in the context.
                 * -- 实例化并调用所有注册的BeanFactoryPostProcessor bean, 如果给出明确的顺序
                 */
                invokeBeanFactoryPostProcessors(beanFactory);

                /**
                 * Register bean processors that intercept bean creation.
                 * -- 注册拦截bean创建的bean处理器(只进行注册操作)
                 */
                registerBeanPostProcessors(beanFactory);

                /**
                 * Initialize message source for this context.
                 * -- 初始化MessageSource,如果没有在上下文中定义,则使用父上下文中定义的
                 */
                initMessageSource();

                /**
                 * Initialize event multicaster for this context.
                 * -- 初始化Spring事件发布器(管理事件监听器(BeanFactory中加载,普通监听器对象添加,移除)+发布事件双重作用),
                 * 如果当前上下文没有定义的话使用SimpleApplicationEventMulticaster
                 */
                initApplicationEventMulticaster();

                /**
                 * Initialize other special beans in specific context subclasses.
          * -- Web-Servlet类型的SpringBoot实现中对应ApplicationContext实现类中该方法用于创建初始化内部的Tomcat容器
*/ onRefresh(); /** * Check for listener beans and register them. * --将实现了接口ApplicationListener的bean作为监听器,不影响其他监听器,可以添加而不是bean。 */ registerListeners(); /** * todo Instantiate all remaining (non-lazy-init) singletons. * -- 实例化所有剩余的(非lazy-init)单例 */ finishBeanFactoryInitialization(beanFactory); /** * Last step: publish corresponding event. * -- 最后一步:发布相应的事件
          * -- Web-Servlet类型的SpringBoot对应的AbstractApplicationContext实现类中该方法用于启动内部Tomcat等容器
*/
                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.  重置active标识为false
                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...
                 * -- 在Spring的核心中重置公共自省缓存,因为我们可能再也不需要单例bean的元数据了…
                 */
                resetCommonCaches();
            }
        }
    }

2.AbstractApplicationContext#refresh方法拆分

1.prepareRefresh- 准备当前需要refresh的上下文,设置其开始时间和活动标识同时处理好各种属性资源配置的初始化操作

  /**
     * Prepare this context for refreshing, setting its startup date and
     * active flag as well as performing any initialization of property sources.
     * -- 准备当前需要refresh的上下文,设置其开始时间和活动标识同时处理好各种属性资源配置的初始化操作
     */
    protected void prepareRefresh() {
        // Switch to active.
        this.startupDate = System.currentTimeMillis();
        // 标记当前上下文处于活跃状态
        this.closed.set(false);
        this.active.set(true);
        if (logger.isInfoEnabled()) {logger.info("Refreshing " + this); }
        /**
         * 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<>();
    }

    /**
     * <p>Replace any stub property sources with actual instances.
     * @see org.springframework.core.env.PropertySource.StubPropertySource
     * @see org.springframework.web.context.support.WebApplicationContextUtils#initServletPropertySources
     */
    protected void initPropertySources() {
        // For subclasses: do nothing by default.
    }

2. obtainFreshBeanFactory- 刷新内部beanFactory

  protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
        refreshBeanFactory();
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (logger.isDebugEnabled()) {
            logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
        }
        return beanFactory;
    }
    protected abstract void refreshBeanFactory() throws BeansException, IllegalStateException;
    @Override
    public abstract ConfigurableListableBeanFactory getBeanFactory() throws IllegalStateException;

AbstractApplicationContext类有两个子类:GenericApplicationContext和AbstractRefreshableApplicationContext

  • GenericApplicationContext:  及其子类持有一个单例固定的DefaultListableBeanFactory实例,在创建GenericApplicationContext实例时就会创建DefaultListableBeanFactory实例, 固定的意思就是说即使调用refresh方法也不会重新创建BeanFactory实例

    •   SpringBoot的Web-Servlet实现是继承自该子类   
  @Override
    protected final void refreshBeanFactory() throws IllegalStateException {
        if (!this.refreshed.compareAndSet(false, true)) {
            throw new IllegalStateException("GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once");
        }
        this.beanFactory.setSerializationId(getId());
    }
  @Override
    public final ConfigurableListableBeanFactory getBeanFactory() {
        return this.beanFactory;
    }
  • AbstractRefreshableApplicationContext: 它实现了所谓的热刷新功能,它内部也持有一个DefaultListableBeanFactory实例,每次刷新refresh()时都会销毁当前的BeanFactory实例并重新创建DefaultListableBeanFactory实例

    @Override
    protected final void refreshBeanFactory() throws BeansException {
        if (hasBeanFactory()) {
            destroyBeans();
            closeBeanFactory();
        }
        try {
            DefaultListableBeanFactory beanFactory = createBeanFactory();
            beanFactory.setSerializationId(getId());
            customizeBeanFactory(beanFactory);
            loadBeanDefinitions(beanFactory);
            this.beanFactory = beanFactory;
        } catch (IOException ex) {
            throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
        }
    }
protected final boolean hasBeanFactory() { return (this.beanFactory != null); }
@Override
protected final void closeBeanFactory() { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory != null) { beanFactory.setSerializationId(null); this.beanFactory = null; } } @Override public final ConfigurableListableBeanFactory getBeanFactory() { DefaultListableBeanFactory beanFactory = this.beanFactory; if (beanFactory == null) { throw new IllegalStateException("BeanFactory not initialized or already closed - " + "call 'refresh' before accessing beans via the ApplicationContext"); } return beanFactory; } protected DefaultListableBeanFactory createBeanFactory() { return new DefaultListableBeanFactory(getInternalParentBeanFactory()); }

3. prepareBeanFactory-配置工厂的标准上下文特征属性,例如类加载器,Bean处理器,事件发布器,运行环境,属性资源注册器,Bean表达式处理器等

  /**
     * Configure the factory's standard context characteristics,
     * such as the context's ClassLoader and post-processors.
     * --配置工厂的标准上下文特征属性,例如类加载器,Bean处理器,事件发布器,运行环境,属性资源注册器,Bean表达式处理器等
     * @param beanFactory the BeanFactory to configure
     */
    protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // Tell the internal bean factory to use the context's class loader etc.
        beanFactory.setBeanClassLoader(getClassLoader());
        beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
        beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

        // Configure the bean factory with context callbacks.
        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.
        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.
        beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

        // Detect a LoadTimeWeaver and prepare for weaving, if found.
        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.  注册默认环境相关的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());
        }
    }

4. postProcessBeanFactory-注册request|session|application 的作用域(相关依赖组件) + 添加一个ServletContextAwareProcessor处理器 + 注册环境中的Beans(servletContext servletConfig contextParameters contextAttributes)

protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) { }

  AbstractApplicationContext类有两个子类:GenericApplicationWebContext(GenericApplicationContext子类)和AbstractRefreshableApplicationContext

  • GenericApplicationWebContext

  @Override
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        if (this.servletContext != null) {
            beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext));
            beanFactory.ignoreDependencyInterface(ServletContextAware.class);
        }
        WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
        WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext);
    }
  • AbstractRefreshableApplicationContext

  /**
     * Register request/session/application scopes, a {@link ServletContextAwareProcessor}, etc.
     * -- 注册request|session|application 的作用域(相关依赖组件) + 添加一个ServletContextAwareProcessor + 注册环境中的Beans
     */
    @Override
    protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
        // 针对实现接口ServletContextAware的bean在初始化之前回调设置 ServletContext ServletConfig
        beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
        beanFactory.ignoreDependencyInterface(ServletContextAware.class);
        beanFactory.ignoreDependencyInterface(ServletConfigAware.class);

        // 注册request|session|application 的作用域(相关依赖组件)
        WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);

        // 注册Servlet相关的Bean组件 servletContext  servletConfig contextParameters contextAttributes
        WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
    }

5. invokeBeanFactoryPostProcessors-实例化并调用所有注册的BeanFactoryPostProcessor bean, 如果给出明确的顺序  

    /** Instantiate and invoke all registered BeanFactoryPostProcessor beans,
     * respecting explicit order if given.
     * -- 实例化并调用所有注册的BeanFactoryPostProcessor bean, 如果给出明确的顺序
     * <p>Must be called before singleton instantiation.
     */
    protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors()); // 代码较长较复杂,总体就是按照顺序优先级处理(实现Order|PriorityOrdered接口),其次处理一般的 
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime // (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
  if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
     beanFactory.addBeanPostProcessor(
new LoadTimeWeaverAwareProcessor(beanFactory));
    beanFactory.setTempClassLoader(
new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
  }
}

6. registerBeanPostProcessors-注册拦截bean创建的bean处理器(只进行注册操作)

  /**
     * Instantiate and register all BeanPostProcessor beans,
     * respecting explicit order if given.
     * <p>Must be called before any instantiation of application beans.
     */
    protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
        PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this); // 代码较长较复杂,总体就是按照顺序优先级处理(实现Order|PriorityOrdered接口),其次处理一般的
  }

7. initMessageSource-初始化MessageSource,如果没有在上下文中定义,则使用父上下文中定义的

  /**
     * Initialize the MessageSource.
     * Use parent's if none defined in this context.
     * -- 初始化MessageSource,如果没有在上下文中定义,则使用父上下文中定义的
     */
    protected void initMessageSource() {
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        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.isDebugEnabled()) {
                logger.debug("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.isDebugEnabled()) {
                logger.debug("Unable to locate MessageSource with name '" + MESSAGE_SOURCE_BEAN_NAME +
                        "': using default [" + this.messageSource + "]");
            }
        }
    }
    
     @Nullable
    protected MessageSource getInternalParentMessageSource() {
        return (getParent() instanceof AbstractApplicationContext ?
                ((AbstractApplicationContext) getParent()).messageSource : getParent());
    }

8. initApplicationEventMulticaster-初始化Spring事件发布器(管理事件监听器(BeanFactory中加载,普通监听器对象添加,移除)+发布事件双重作用), 如果当前上下文没有定义的话使用SimpleApplicationEventMulticaster

  /**
     * Initialize the ApplicationEventMulticaster.
     * Uses SimpleApplicationEventMulticaster if none defined in the context.
     * @see org.springframework.context.event.SimpleApplicationEventMulticaster
     * -- 初始化Spring事件发布器,如果当前上下文没有定义的话使用SimpleApplicationEventMulticaster(applicationEventMulticaster)
     */
    protected void initApplicationEventMulticaster() {
        ConfigurableListableBeanFactory beanFactory = getBeanFactory();
        if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
            this.applicationEventMulticaster =
                    beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
            if (logger.isDebugEnabled()) {
                logger.debug("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
            }
        } else {
            this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
            beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
            if (logger.isDebugEnabled()) {
                logger.debug("Unable to locate ApplicationEventMulticaster with name '" +
                        APPLICATION_EVENT_MULTICASTER_BEAN_NAME +
                        "': using default [" + this.applicationEventMulticaster + "]");
            }
        }
    }

9. onRefresh方法

  protected void onRefresh() throws BeansException {
        // For subclasses: do nothing by default.
    }

GenericApplicationWebContext(GenericApplicationContext子类)和AbstractRefreshableApplicationContext 实现方式一样

@Override
protected void onRefresh() {
   this.themeSource = UiApplicationContextUtils.initThemeSource(this);
}

10. registerListeners - 将实现了接口ApplicationListener的bean作为监听器,不影响其他监听器,可以添加而不是bean。

    /**
     * Add beans that implement ApplicationListener as listeners.
     * Doesn't affect other listeners, which can be added without being beans.
     * -- 将实现了接口ApplicationListener的bean作为监听器,不影响其他监听器,可以添加而不是bean。
     */
    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!
         *     其次从BeanFactory中获取ApplicationListener类型的bean,将它们也当作监听器纳入到
         *     SimpleApplicationEventMulticaster的管理中
         */
        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);
            }
        }
    }

11. finishBeanFactoryInitialization -实例化所有剩余的(非lazy-init)单例

    /**
     * Finish the initialization of this context's bean factory,
     * initializing all remaining singleton beans.
     * -- 完成此上下文的bean工厂的初始化, 初始化所有剩余的单例bean。
     */
    protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
        /**
         * Initialize conversion service for this context.  -- 初始化当前上下文的转换服务 conversionService
         */
        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.
         * -- 注册一个内置的占位符值处理器如果之前没有注册post-processor bean(例如PropertyPlaceholderConfigurer)
         */
        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);
        }

        /**
         *  Stop using the temporary ClassLoader for type matching. -- 停止使用临时ClassLoader进行类型匹配。
         */
        beanFactory.setTempClassLoader(null);

        /**
         * Allow for caching all bean definition metadata, not expecting further changes.
         * -- 冻结配置信息,允许缓存所有bean定义元数据,而不期望进一步更改
         */
        beanFactory.freezeConfiguration();

        /**
         * todo Instantiate all remaining (non-lazy-init) singletons.
         *  -- 实例化所有剩余的(非lazy-init)单例。
         *  -- {@see DefaultListableBeanFactory#preInstantiateSingletons() }
         */
        beanFactory.preInstantiateSingletons();
    }
DefaultListableBeanFactory.preInstantiateSingletons方法追踪
  /**
     *  实例化所有剩余的(非lazy-init)单例
     * @throws BeansException
     */
    @Override
    public void preInstantiateSingletons() throws BeansException {
        if (logger.isDebugEnabled()) { logger.debug("Pre-instantiating singletons in " + this);}
        /**
         * Iterate over a copy to allow for init methods which in turn register new bean definitions.
         *     While this may not be part of the regular factory bootstrap, it does otherwise work fine
         *     -- 遍历一个副本以允许init方法注册新的bean定义。虽然这可能不是常规的工厂引导的一部分,但它可以正常工作
         */
        List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
        /**
         * Trigger initialization of all non-lazy singleton beans...
         * -- 触发所有非懒加载的bean的初始化操作
         */
        for (String beanName : beanNames) {
            // 针对beanName获取一个经过merge之后的处于顶层的Bean定义 RootBeanDefinition
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            // 当前bean是非抽象的,单例模式,非懒加载的
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
                // 判断如果当前Bean是工厂Bean,则需要从工厂中获取Bean
                if (isFactoryBean(beanName)) {
                    Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
                    if (bean instanceof FactoryBean) {
                        FactoryBean<?> factory = (FactoryBean<?>) bean;
                        boolean isEagerInit;
                        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 {
                    // 关键方法在于此getBean(beanName)
                    getBean(beanName);
                }
            }
        }
        /**
         * Trigger post-initialization callback for all applicable beans...
         * -- 触发所有Bean的后置处理回调方法
         */
        for (String beanName : beanNames) {
            // 获取单例Bean
            Object singletonInstance = getSingleton(beanName);
            if (singletonInstance instanceof SmartInitializingSingleton) {
                SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                        smartSingleton.afterSingletonsInstantiated();
                        return null;
                    }, getAccessControlContext());
                } else {
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }
AbstractBeanFactory#getBean(beanName)方法追踪
@Override
    public Object getBean(String name) throws BeansException {
        return doGetBean(name, null, null, false);
    }
    protected <T> T doGetBean(String name, @Nullable Class<T> requiredType, @Nullable Object[] args, boolean typeCheckOnly)throws BeansException {
        String beanName = transformedBeanName(name);
        Object bean;
        /*Eagerly check singleton cache for manually registered singletons.-- 检查手动注册的单例缓存*/
        Object sharedInstance = getSingleton(beanName);
        if (sharedInstance != null && args == null) {
            if (logger.isDebugEnabled()) {
                if (isSingletonCurrentlyInCreation(beanName)) {
                    logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +"' that is not fully initialized yet - a consequence of a circular reference");
                } else {
                    logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
                }
            }
            bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
        }else {
            /**
             * Fail if we're already creating this bean instance: We're assumably within a circular reference.
             * -- 如果我们已经在创建这个bean实例,则失败: 我们假定在一个循环引用中
             */
            if (isPrototypeCurrentlyInCreation(beanName)) { throw new BeanCurrentlyInCreationException(beanName);
            }

            // Check if bean definition exists in this factory.
            BeanFactory parentBeanFactory = getParentBeanFactory();
            if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
                // Not found -> check parent.
                String nameToLookup = originalBeanName(name);
                if (parentBeanFactory instanceof AbstractBeanFactory) {
                    return ((AbstractBeanFactory) parentBeanFactory).doGetBean(
                            nameToLookup, requiredType, args, typeCheckOnly);
                } else if (args != null) {
                    // Delegation to parent with explicit args.
                    return (T) parentBeanFactory.getBean(nameToLookup, args);
                } else {
                    // No args -> delegate to standard getBean method.
                    return parentBeanFactory.getBean(nameToLookup, requiredType);
                }
            }

            if (!typeCheckOnly) {
                markBeanAsCreated(beanName);
            }

            try {
                RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
                checkMergedBeanDefinition(mbd, beanName, args);

                // Guarantee initialization of beans that the current bean depends on.
                String[] dependsOn = mbd.getDependsOn();
                if (dependsOn != null) {
                    for (String dep : dependsOn) {
                        if (isDependent(beanName, dep)) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "Circular depends-on relationship between '" + beanName + "' and '" + dep + "'");
                        }
                        registerDependentBean(dep, beanName);
                        try {
                            getBean(dep);
                        } catch (NoSuchBeanDefinitionException ex) {
                            throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                                    "'" + beanName + "' depends on missing bean '" + dep + "'", ex);
                        }
                    }
                }

                // todo  Create bean instance.  开始创建bean实例
                if (mbd.isSingleton()) {
                    sharedInstance = getSingleton(beanName, () -> {
                        try {
                            // todo  AbstractAutowireCapableBeanFactory#createBean 方法
                            return createBean(beanName, mbd, args);
                        } catch (BeansException ex) {
                            // Explicitly remove instance from singleton cache: It might have been put there
                            // eagerly by the creation process, to allow for circular reference resolution.
                            // Also remove any beans that received a temporary reference to the bean.
                            destroySingleton(beanName);
                            throw ex;
                        }
                    });
                    bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
                }else if (mbd.isPrototype()) {
                    // It's a prototype -> create a new instance.
                    Object prototypeInstance = null;
                    try {
                        beforePrototypeCreation(beanName);
                        prototypeInstance = createBean(beanName, mbd, args);
                    } finally {
                        afterPrototypeCreation(beanName);
                    }
                    bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
                }else {
                    String scopeName = mbd.getScope();
                    if (!StringUtils.hasLength(scopeName)) {
                        throw new IllegalStateException("No scope name defined for bean ´" + beanName + "'");
                    }
                    Scope scope = this.scopes.get(scopeName);
                    if (scope == null) {
                        throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
                    }
                    try {
                        Object scopedInstance = scope.get(beanName, () -> {
                            beforePrototypeCreation(beanName);
                            try {
                                return createBean(beanName, mbd, args);
                            } finally {
                                afterPrototypeCreation(beanName);
                            }
                        });
                        bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
                    }catch (IllegalStateException ex) {
                        throw new BeanCreationException(beanName,
                                "Scope '" + scopeName + "' is not active for the current thread; consider " +
                                "defining a scoped proxy for this bean if you intend to refer to it from a singleton",
                                ex);
                    }
                }
            }catch (BeansException ex) {
                cleanupAfterBeanCreationFailure(beanName);
                throw ex;
            }
        }

        // Check if required type matches the type of the actual bean instance.
        if (requiredType != null && !requiredType.isInstance(bean)) {
            try {
                T convertedBean = getTypeConverter().convertIfNecessary(bean, requiredType);
                if (convertedBean == null) {
                    throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
                }
                return convertedBean;
            } catch (TypeMismatchException ex) {
                if (logger.isDebugEnabled()) {
                    logger.debug("Failed to convert bean '" + name + "' to required type '" +
                            ClassUtils.getQualifiedName(requiredType) + "'", ex);
                }
                throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
            }
        }
        return (T) bean;
    }
AbstractBeanFactory#getSingleton(beanName) 方法追踪 -- 三级缓存池
  @Nullable
    public Object getSingleton(String beanName) {
        return getSingleton(beanName, true);
    }
    /** -- 三级缓存中获取单例Bean */
    @Nullable
    protected Object getSingleton(String beanName, boolean allowEarlyReference) {
        // step1 从单例对象缓存池中根据名称获取对象
        Object singletonObject = this.singletonObjects.get(beanName);
        // 如果单例对象缓存池中不存在对应BeanName对象或者当前对象正在创建过程中
        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {
            // 使用加锁机制
            synchronized (this.singletonObjects) {
                // step2 其次从提前暴露出来的缓存池中获取
                singletonObject = this.earlySingletonObjects.get(beanName);
                if (singletonObject == null && allowEarlyReference) {
                    /**
                     * step3 最后如果还是获取不到,只能从BeanFactory缓存池中获取当前Bean对应BeanFactory,之后再从BeanFactory获取对象
                     *         同时将对象放入提前暴露的缓存池,将对象对应BeanFactory从工厂缓存池中移除
                     */
                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);
                    if (singletonFactory != null) {
                        singletonObject = singletonFactory.getObject();
                        this.earlySingletonObjects.put(beanName, singletonObject);
                        this.singletonFactories.remove(beanName);
                    }
                }
            }
        }
        return singletonObject;
    }
AbstractAutowireCapableBeanFactory#createBean(beanName) 方法追踪 --创建Bean
  @Override
    protected Object createBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {
        if (logger.isDebugEnabled()) {
            logger.debug("Creating instance of bean '" + beanName + "'");
        }
        RootBeanDefinition mbdToUse = mbd;

        // Make sure bean class is actually resolved at this point, and
        // clone the bean definition in case of a dynamically resolved Class
        // which cannot be stored in the shared merged bean definition.
        Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
        if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
            mbdToUse = new RootBeanDefinition(mbd);
            mbdToUse.setBeanClass(resolvedClass);
        }
        // Prepare method overrides.
        try {
            mbdToUse.prepareMethodOverrides();
        } catch (BeanDefinitionValidationException ex) {
            throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(), beanName, "Validation of method overrides failed", ex);
        }
        try {
            // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
            // 给BeanPostProcessors一个返回代理而不是目标bean实例的机会,执行Bean的前置和后置处理方法
            Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
            if (bean != null) {
                return bean;
            }
        } catch (Throwable ex) {
            throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName, "BeanPostProcessor before instantiation of bean failed", ex);
        }
        try {
            // 开始创建Bean
            Object beanInstance = doCreateBean(beanName, mbdToUse, args);
            if (logger.isDebugEnabled()) {
                logger.debug("Finished creating instance of bean '" + beanName + "'");
            }
            return beanInstance;
        } catch (BeanCreationException | ImplicitlyAppearedSingletonException ex) {
            // A previously detected exception with proper bean creation context already,
            // or illegal singleton state to be communicated up to DefaultSingletonBeanRegistry.
            throw ex;
        } catch (Throwable ex) {
            throw new BeanCreationException( mbdToUse.getResourceDescription(), beanName, "Unexpected exception during bean creation", ex);
        }
    }
AbstractAutowireCapableBeanFactory#doCreateBean(beanName) 方法追踪 --创建Bean 
  protected Object doCreateBean(String beanName, RootBeanDefinition mbd, @Nullable Object[] args)
            throws BeanCreationException {
        // Instantiate the bean. Bean包装类
        BeanWrapper instanceWrapper = null;
        // 如果Bean是单例,先从工厂Bean实例缓存中移除该BeanName对应包装类并赋值给instanceWrapper
        if (mbd.isSingleton()) {
            instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
        }
        // 如果instanceWrapper为空则需要创建一个Bean实例
        if (instanceWrapper == null) {
            instanceWrapper = createBeanInstance(beanName, mbd, args);
        }
        Object bean = instanceWrapper.getWrappedInstance();
        Class<?> beanType = instanceWrapper.getWrappedClass();
        if (beanType != NullBean.class) {
            mbd.resolvedTargetType = beanType;
        }
        // Allow post-processors to modify the merged bean definition. 允许后处理器修改合并的bean定义
        synchronized (mbd.postProcessingLock) {
            if (!mbd.postProcessed) {
                try {
                    applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
                } catch (Throwable ex) {
                    throw new BeanCreationException(mbd.getResourceDescription(), beanName,
                            "Post-processing of merged bean definition failed", ex);
                }
                mbd.postProcessed = true;
            }
        }
        /**
         * Eagerly cache singletons to be able to resolve circular references
         *  even when triggered by lifecycle interfaces like BeanFactoryAware.
         *  -- 提前地单例缓存池是为了保证循环依赖的,尤其是由像BeanFactoryAware这样的生命周期接口触发的
         */
        boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
                isSingletonCurrentlyInCreation(beanName));
        if (earlySingletonExposure) {
            if (logger.isDebugEnabled()) {
                logger.debug("Eagerly caching bean '" + beanName + "' to allow for resolving potential circular references");
            }
            // 如果需要提前暴露单例对象(还未初始化完毕的半成品Bean)
            addSingletonFactory(beanName, () -> getEarlyBeanReference(beanName, mbd, bean));
        }
        // Initialize the bean instance.  开始初始化Bean
        Object exposedObject = bean;
        try {
            // 处理Bean的属性依赖(依赖注入Bean相关属性)
            populateBean(beanName, mbd, instanceWrapper);
            // 初始化Bean
            exposedObject = initializeBean(beanName, exposedObject, mbd);
        } catch (Throwable ex) {
            if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
                throw (BeanCreationException) ex;
            } else {
                throw new BeanCreationException( mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
            }
        }

        // 当前Bean需要提前暴露时
        if (earlySingletonExposure) {
            Object earlySingletonReference = getSingleton(beanName, false);
            if (earlySingletonReference != null) {
                if (exposedObject == bean) {
                    exposedObject = earlySingletonReference;
                } else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
                    String[] dependentBeans = getDependentBeans(beanName);
                    Set<String> actualDependentBeans = new LinkedHashSet<>(dependentBeans.length);
                    for (String dependentBean : dependentBeans) {
                        if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
                            actualDependentBeans.add(dependentBean);
                        }
                    }
                    if (!actualDependentBeans.isEmpty()) {
                        throw new BeanCurrentlyInCreationException(beanName,
                                "Bean with name '" + beanName + "' has been injected into other beans [" +
                                StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
                                "] in its raw version as part of a circular reference, but has eventually been " +
                                "wrapped. This means that said other beans do not use the final version of the " +
                                "bean. This is often the result of over-eager type matching - consider using " +
                                "'getBeanNamesForType' with the 'allowEagerInit' flag turned off, for example.");
                    }
                }
            }
        }

        // Register bean as disposable.  将Bean注册成为一个可销毁(如果实现了接口或者声明了DestroyMethod方法)
        try {
            registerDisposableBeanIfNecessary(beanName, bean, mbd);
        } catch (BeanDefinitionValidationException ex) {
            throw new BeanCreationException(
                    mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
        }
        return exposedObject;
    }
AbstractAutowireCapableBeanFactory#populateBean|initializeBean方法追踪 --初始化Bean+组装bean属性
protected void populateBean(String beanName, RootBeanDefinition mbd, @Nullable BeanWrapper bw) {
        if (bw == null) {
            if (mbd.hasPropertyValues()) {
                throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
            } else {
                // Skip property population phase for null instance.
                return;
            }
        }

        // Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
        // state of the bean before properties are set. This can be used, for example,
        // to support styles of field injection.
        if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
            for (BeanPostProcessor bp : getBeanPostProcessors()) {
                if (bp instanceof InstantiationAwareBeanPostProcessor) {
                    // 执行InstantiationAwareBeanPostProcessor处理器方法
                    InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                    if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
                        return;
                    }
                }
            }
        }

        // 当前对象的属性
        PropertyValues pvs = (mbd.hasPropertyValues() ? mbd.getPropertyValues() : null);
        // 获取当前对象属性装配方式(构造器,setter方法,自动装配)
        int resolvedAutowireMode = mbd.getResolvedAutowireMode();
        if (resolvedAutowireMode == AUTOWIRE_BY_NAME || resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
            MutablePropertyValues newPvs = new MutablePropertyValues(pvs);
            // Add property values based on autowire by name if applicable.  根据名称实现属性的自动装配
            if (resolvedAutowireMode == AUTOWIRE_BY_NAME) {
                autowireByName(beanName, mbd, bw, newPvs);
            }
            // Add property values based on autowire by type if applicable.  根据类型实现属性的自动装配
            if (resolvedAutowireMode == AUTOWIRE_BY_TYPE) {
                autowireByType(beanName, mbd, bw, newPvs);
            }
            pvs = newPvs;
        }

        // 当前对象是否还有更多的InstantiationAwareBeanPostProcessors处理器
        boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
        boolean needsDepCheck = (mbd.getDependencyCheck() != AbstractBeanDefinition.DEPENDENCY_CHECK_NONE);

        if (hasInstAwareBpps || needsDepCheck) {
            if (pvs == null) {
                pvs = mbd.getPropertyValues();
            }
            PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
            if (hasInstAwareBpps) {
                for (BeanPostProcessor bp : getBeanPostProcessors()) {
                    if (bp instanceof InstantiationAwareBeanPostProcessor) {
                        InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
                        // 执行InstantiationAwareBeanPostProcessor的postProcessPropertyValues方法
                        pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
                        if (pvs == null) {
                            return;
                        }
                    }
                }
            }
            if (needsDepCheck) {
                checkDependencies(beanName, mbd, filteredPds, pvs);
            }
        }
        if (pvs != null) {
            // 最终将对象的属性设置进去
            applyPropertyValues(beanName, mbd, bw, pvs);
        }
    }
    
    protected Object initializeBean(String beanName, Object bean, @Nullable RootBeanDefinition mbd) {
        if (System.getSecurityManager() != null) {
            AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
                invokeAwareMethods(beanName, bean);
                return null;
            }, getAccessControlContext());
        } else {
            // 调用对象实现的各种 Aware回调接口方法
            invokeAwareMethods(beanName, bean);
        }

        Object wrappedBean = bean;
        if (mbd == null || !mbd.isSynthetic()) {
            // 调用Bean实现的BeanPostProcessors前置处理器方法
            wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
        }
        try {
            // 调用Bean实现接口InitializingBean的初始化方法+自定义初始化方法
            invokeInitMethods(beanName, wrappedBean, mbd);
        } catch (Throwable ex) {
            throw new BeanCreationException(
                    (mbd != null ? mbd.getResourceDescription() : null),
                    beanName, "Invocation of init method failed", ex);
        }
        if (mbd == null || !mbd.isSynthetic()) {
            wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
        }
        return wrappedBean;
    }

12. finishRefresh-完成刷新:发布相应的事件

  protected void finishRefresh() {
        /*Clear context-level resource caches (such as ASM metadata from scanning).-- 清除上下文级资源缓存(例如扫描ASM元数据)。*/
        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 MBean,如果是活动的*/
        LiveBeansView.registerApplicationContext(this);
    }

13. 启动异常处理 destroyBeans+cancelRefresh

    protected void destroyBeans() {
        getBeanFactory().destroySingletons();
    }
    protected void cancelRefresh(BeansException ex) {
        this.active.set(false);
    }    

14. resetCommonCaches-在Spring的核心中重置公共自省缓存

 protected void resetCommonCaches() {
        ReflectionUtils.clearCache();
        AnnotationUtils.clearCache();
        ResolvableType.clearCache();
        CachedIntrospectionResults.clearClassLoader(getClassLoader());
 }

 

 

 

posted @ 2021-07-02 17:08  521pingguo1314  阅读(304)  评论(0编辑  收藏  举报