Spring容器创建流程(9)完成创建

Spring的refresh() 方法中finishRefresh()方法完成之后也就代表着,Spring容器真正的创建完成了。下面看finishRefresh()的源码。

容器refresh总览:

		synchronized (this.startupShutdownMonitor) {
     
			// 设置环境,校验参数。
			prepareRefresh();
			
			// 创建BeanFactory(DefaultListableBeanFactor),加载bean定义信息。
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 对BeanFactory设置	
			prepareBeanFactory(beanFactory);

			try {
     
				// 留给子类去实现,完成对beanFactory的自定义处理
				postProcessBeanFactory(beanFactory);

				// 调用beanFactory的后置处理器
				invokeBeanFactoryPostProcessors(beanFactory);

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

				// 初始化messageSource,国际化支持
				initMessageSource();

				// 初始化事件派发器
				initApplicationEventMulticaster();

				// 留给子类实现,自定义处理
				onRefresh();

				// 注册事件监听器
				registerListeners();

				// 初始化所有剩余的非懒加载的单实例bean
				finishBeanFactoryInitialization(beanFactory);

				// 完成容器
				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 {
     
				// 资源缓存的清除
				resetCommonCaches();
			}
		}


finishRefresh

完成创建容器的最后一些处理工作(事件通知)

	protected void finishRefresh() {
     
		// 清除加载Recource缓存,(resource在加载beanDefinition的时候说过)
		clearResourceCaches();

		// 初始化生命周期处理器
		initLifecycleProcessor();

		// 调用初始化的声明周期处理器的,onRefresh
		getLifecycleProcessor().onRefresh();

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

		// 对jmx bean管理进行支持注册
		LiveBeansView.registerApplicationContext(this);
	}

声明周期处理器初始化

	protected void initLifecycleProcessor() {
     
		ConfigurableListableBeanFactory beanFactory = getBeanFactory();
		// 如果容器中已经有了一个名为lifecycleProcessor的生命周期处理器,那么用已经存在的
		if (beanFactory.containsLocalBean(LIFECYCLE_PROCESSOR_BEAN_NAME)) {
     
			this.lifecycleProcessor =
					beanFactory.getBean(LIFECYCLE_PROCESSOR_BEAN_NAME, LifecycleProcessor.class);
			if (logger.isDebugEnabled()) {
     
				logger.debug("Using LifecycleProcessor [" + this.lifecycleProcessor + "]");
			}
		}
		else {
     
		// 创建一个默认的生命周期处理器
			DefaultLifecycleProcessor defaultProcessor = new DefaultLifecycleProcessor();
			defaultProcessor.setBeanFactory(beanFactory);
			this.lifecycleProcessor = defaultProcessor;
			// 生命周期处理器添加到容器中
			beanFactory.registerSingleton(LIFECYCLE_PROCESSOR_BEAN_NAME, this.lifecycleProcessor);
			if (logger.isDebugEnabled()) {
     
				logger.debug("Unable to locate LifecycleProcessor with name '" +
						LIFECYCLE_PROCESSOR_BEAN_NAME +
						"': using default [" + this.lifecycleProcessor + "]");
			}
		}
	}

默认的声明周期处理器做了什么。
会调用给定生命周期处理器的onRefresh方法。

	@Override
	public void onRefresh() {
     
		startBeans(true);
		this.running = true;
	}

	private void startBeans(boolean autoStartupOnly) {
     
	// 获取所有Lifecycle子类
		Map<String, Lifecycle> lifecycleBeans = getLifecycleBeans();
		Map<Integer, LifecycleGroup> phases = new HashMap<>();
		lifecycleBeans.forEach((beanName, bean) -> {
     
		// 如果只是自动启动的话,会把SmartLifecycle从容器中挑选出来
			if (!autoStartupOnly || (bean instanceof SmartLifecycle && ((SmartLifecycle) bean).isAutoStartup())) {
     
				int phase = getPhase(bean);
				LifecycleGroup group = phases.get(phase);
				if (group == null) {
     
				// SmartLifecycle实现了Phased接口,getPhase表名自己的阶段
				// 按照阶段创建对应的阶段周期组
					group = new LifecycleGroup(phase, this.timeoutPerShutdownPhase, lifecycleBeans, autoStartupOnly);
				// 保存所有的阶段
					phases.put(phase, group);
				}
				// 对应的阶段,添加对应的smartLifecycle
				group.add(beanName, bean);
			}
		});
		// 调用每个阶段中的SmartLifecycle的start方法
		if (!phases.isEmpty()) {
     
			List<Integer> keys = new ArrayList<>(phases.keySet());
			Collections.sort(keys);
			for (Integer key : keys) {
     
				phases.get(key).start();
			}
		}
	}

自此容器的创建就完成了。

你可能感兴趣的:(死磕Spring,spring源码分析)