spring IOC - AnnotationConfigApplicationContext#refresh2

执行完前面的步骤后, 回到 org.springframework.context.support.AbstractApplicationContext#refresh 方法.

@Override
public void refresh() throws BeansException, IllegalStateException {
    synchronized (this.startupShutdownMonitor) {
        // Prepare this context for refreshing.
        //准备工作包括设置启动时间,是否激活标识位, 初始化属性源(property source)配置
        //不重要
        prepareRefresh();

        // Tell the subclass to refresh the internal bean factory.
        //返回一个factory  - 为什么需要返回一个工厂
        //因为要对工厂进行初始化
        ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

        // Prepare the bean factory for use in this context.
        //为beanFactory设置一些属性如ClassLoader,BeanExpressionResolver,PropertyEditorRegistrar,BeanPostProcessor等
        //准备工厂
        prepareBeanFactory(beanFactory);

        try {
            // Allows post-processing of the bean factory in context subclasses.
            //这个方法在当前版本的spring是没用任何代码的
            //可能spring期待在后面的版本中去扩展吧
            postProcessBeanFactory(beanFactory);

            // Invoke factory processors registered as beans in the context.
            //为beanFactory注册BeanFactoryPostProcessor
            //在spring的环境中去执行已经被注册的 factory processors
            //设置执行自定义的ProcessBeanFactory 和spring内部自己定义的
            invokeBeanFactoryPostProcessors(beanFactory);

            // Register bean processors that intercept bean creation.
            //按照顺序注册当Bean创建时候的BeanPostProcessor
            //1. 注册实现了 PriorityOrdered 接口的后置处理器
            //2. 注册实现了 Ordered 接口的后置处理器
            //3. 注册其他的后置处理器
            registerBeanPostProcessors(beanFactory);

            // Initialize message source for this context.
            //初始化上下文的消息源:DelegatingMessageSource
            initMessageSource();

            // Initialize event multicaster for this context.
            //初始化了一个事件广播器:SimpleApplicationEventMulticaster
            initApplicationEventMulticaster();

            // Initialize other special beans in specific context subclasses.
            //空方法, 留着后面扩展用的
            onRefresh();

            // Check for listener beans and register them.
            //获取ApplicationListener,并在事件传播器中注册他们
            registerListeners();

            // Instantiate all remaining (non-lazy-init) singletons.
            //获取LoadTimeWeaverAware并初始化他们,初始化单例并且非懒加载的Bean
            finishBeanFactoryInitialization(beanFactory);

            // Last step: publish corresponding event.
            //完成refresh Context操作,初始化LifecycleProcessor并start,发布ContextRefreshedEvent事件
            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();
        }
    }
}

refresh 方法, 除了  invokeBeanFactoryPostProcessors() 比较重要外, 还有一个很重要的方法: finishBeanFactoryInitialization(beanFactory)

其他的几个方法, 看看就行, 都是一些注册, 初始化一些默认属性什么的, 属于前期的配置工作.

finishBeanFactoryInitialization

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
    // Initialize conversion service for this context.
    if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) &&
            beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) {
        beanFactory.setConversionService(
                beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class));
    }

    // Register a default embedded value resolver if no bean post-processor
    // (such as a PropertyPlaceholderConfigurer bean) registered any before:
    // at this point, primarily for resolution in annotation attribute values.
    if (!beanFactory.hasEmbeddedValueResolver()) {
        //设置一个内置的类型转换器 : StringValueResolver
        beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
    }

    // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
    // aspectj的, 基本用不着
    String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
    for (String weaverAwareName : weaverAwareNames) {
        getBean(weaverAwareName);
    }

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

    // Allow for caching all bean definition metadata, not expecting further changes.
    // 冻结配置
    beanFactory.freezeConfiguration();

    // Instantiate all remaining (non-lazy-init) singletons.
    //实例化所有的单例对象
    beanFactory.preInstantiateSingletons();
}

preInstantiateSingletons 方法中, 就回去实例化容器里面注册的 bean.

//org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons
@Override
public void preInstantiateSingletons() throws BeansException {
    if (logger.isTraceEnabled()) {
        logger.trace("Pre-instantiating singletons in " + this);
    }
    //所有bean的名字
    // Iterate over a copy to allow for init methods which in turn register new bean definitions.
    // While this may not be part of the regular factory bootstrap, it does otherwise work fine.
    List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    // 触发所有非延迟加载单例beans的初始化,主要步骤为调用getBean
    for (String beanName : beanNames) {
        //属性合并 : 合并父 BeanDefinition, xml中 bean 配置 parent=""
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
        // 非抽象 & 单例 & 非懒加载
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
            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 {
                        isEagerInit = (factory instanceof SmartFactoryBean &&
                                ((SmartFactoryBean<?>) factory).isEagerInit());
                    }
                    if (isEagerInit) {
                        getBean(beanName);
                    }
                }
            }
            else {
                getBean(beanName);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    //当所有的bean都完成创建后, 调用他们的 SmartInitializingSingleton 接口的 afterSingletonsInstantiated 方法
    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. 首先遍历了容器里面注册的 beanName , 然后通过 getBean() 的方式, 将 beanName 转化成 bean.

2. 然后遍历所有的 bean, 调用其 SmartInitializingSingleton#afterSingletonsInstantiated() , 进行最后的初始化调用

猜你喜欢

转载自www.cnblogs.com/elvinle/p/13305409.html
今日推荐