Spring Bean生命周期-finishBeanFactoryInitialization(九)

这个方法应该是ApplicationContext刷新的时候,最重要的方法了,因为所有的bean,如果不是lazy-init的都会在这一步进行实例化,并且做一些处理。

狭义上的Bean生命周期就在这一步进行完成,我们一起看看

  //结束context的bean Factory实例化,然后实例化所有的非懒加载单例。
    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));
        }

        // 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.
        // 停止使用临时的类加载器
        beanFactory.setTempClassLoader(null);

        // Allow for caching all bean definition metadata, not expecting further changes.
        //缓存所有的bean definition数据,不期望以后会改变
        beanFactory.freezeConfiguration();

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

分析

  1. ConversionService是一个服务接口用于类型转换,这也是转换系统的入口点。 这一步没有做什么处理
// 如果有ConversionService的Bean,就设置
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));
        }
  1. 先获取实现了LoadTimeWeaverAware接口的bean名称,LoadTimeWeaverAware是类加载时织入的意思。getBean则是让实现LoadTimeWeaverAware的对象提前实例化。
        // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
        String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
        for (String weaverAwareName : weaverAwareNames) {
            getBean(weaverAwareName);
        }
  1. 冻结之前beandifinition的配置,留作后面的缓存用
beanFactory.freezeConfiguration();

public void freezeConfiguration() {
        this.configurationFrozen = true;
        this.frozenBeanDefinitionNames = StringUtils.toStringArray(this.beanDefinitionNames);
}
  1. 实例化所有的non-lazy-init单例,bean真正实例化的时刻到了

基本逻辑,首先获取beanDefinitionNames,查看对应beanName的是否是FactoryBean,不管是不是,最后都要执行getBean方法,getBean方法内部做了实例化Bean的操作。

实例化单例Bean之后,如果Bean实现了SmartInitializingSingleton,就执行afterSingletonsInstantiated方法。


    public void preInstantiateSingletons() throws BeansException {
        if (this.logger.isDebugEnabled()) {
            this.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.
        // 首先将bean difinition赋值到一个新的集合中。
        List beanNames = new ArrayList(this.beanDefinitionNames);

        // Trigger initialization of all non-lazy singleton beans...
        // 出发单例的实例化
        for (String beanName : beanNames) {
            RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
            
            // 不是abstract,不是lazy-init,但是是singleton的才执行如下
            if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
               //是否为FactoryBean,不是的话直接getBean(beanName),也就是实例化
               // 如果是FactoryBean,判断FactoryBean有没有额外的配置
                if (isFactoryBean(beanName)) {
                    final FactoryBean factory = (FactoryBean) getBean(FACTORY_BEAN_PREFIX + beanName);
                    boolean isEagerInit;
                    if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
                        isEagerInit = AccessController.doPrivileged(new PrivilegedAction() {
                            @Override
                            public Boolean run() {
                                return ((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的post-initialization 回调
        for (String beanName : beanNames) {
           //获取Bean的实例
            Object singletonInstance = getSingleton(beanName);
            // 如果实例实现了SmartInitializingSingleton,执行afterSingletonsInstantiated方法。
            if (singletonInstance instanceof SmartInitializingSingleton) {
                final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
                if (System.getSecurityManager() != null) {
                    AccessController.doPrivileged(new PrivilegedAction() {
                        @Override
                        public Object run() {
                            smartSingleton.afterSingletonsInstantiated();
                            return null;
                        }
                    }, getAccessControlContext());
                }
                else {
                    smartSingleton.afterSingletonsInstantiated();
                }
            }
        }
    }
 
 

最后

Bean的实例化大流程,现在我们已经有了概念,下次一起看bean实例化的真正细节。

你可能感兴趣的:(Spring Bean生命周期-finishBeanFactoryInitialization(九))