spring-容器4-初始化完成

容器初始化总体流程

  • 初始化conversion service
  • 对LoadTimeWeaverAware接口bean进行实例化,依赖注入等初始化
  • 冻结配置,beanDefinition不可再修改
  • 预实例化非lazy-init配置的单例bean
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));
    }

    // 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);
    }

    // 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();
}

9.1 非lazy-init

  • 1 遍历beanDefinitionNames数组,
  • 2 获取name对应的beanDefinition,对于单例bean,没abstract,且为这是lazy-init属性的,则进行初始化.
  • 3 对于工厂bean,&+bean name表示工厂bean本身,根据名字获取对应beanDefinition, getBean()初始化bean实例,依赖注入
  • 4 非工厂bean, getBean()初始化bean实例,依赖注入
  • 5 遍历name,获取单例bean对象中SmartInitializingSingleton接口类型的对象。
  • 6 调用接口方法,在所有单例bean实例化完成后,进行一些后置处理
public void preInstantiateSingletons() throws BeansException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Pre-instantiating singletons in " + this);
    }

    List beanNames = new ArrayList(this.beanDefinitionNames);

    // Trigger initialization of all non-lazy singleton beans...
    for (String beanName : beanNames) {//1
        RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);//2
        if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {//2
            if (isFactoryBean(beanName)) {//3
                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 {//4
                getBean(beanName);
            }
        }
    }

    // Trigger post-initialization callback for all applicable beans...
    for (String beanName : beanNames) {
        Object singletonInstance = getSingleton(beanName);
        if (singletonInstance instanceof SmartInitializingSingleton) {//5
            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();//6
            }
        }
    }
}
 
 

十 容器初始化完成函数

  • 初始化生命周期管理器
  • 刷新生命周期接口bean
  • 发送容器更新完成事件
  • 注册mbean
protected void finishRefresh() {
    // 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.registerApplicationContext(this);
}

10.1 生命周期管理bean自动启动

  • 获取Lifecycle接口实现bean
  • 遍历配置自动启动的bean
  • 获取bean生命周期阶段,同阶段放到一个组中
  • 按阶段依次调用bean的start函数,启动bean。
private void startBeans(boolean autoStartupOnly) {
    Map lifecycleBeans = getLifecycleBeans();
    Map phases = new HashMap();
    for (Map.Entry entry : lifecycleBeans.entrySet()) {
        Lifecycle bean = entry.getValue();
        if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
            int phase = getPhase(bean);
            LifecycleGroup group = phases.get(phase);
            if (group == null) {
                group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
                phases.put(phase, group);
            }
            group.add(entry.getKey(), bean);
        }
    }
    if (phases.size() > 0) {
        List keys = new ArrayList(phases.keySet());
        Collections.sort(keys);
        for (Integer key : keys) {
            phases.get(key).start();
        }
    }
}

你可能感兴趣的:(spring-容器4-初始化完成)