AbstractApplicationContext源碼分析

一 refresh源碼分析

@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
                        //準備刷新上下文環境
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
                        //初始化beanfactory,並進行xml文件讀取
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
                        //對BeanFactory進行各類功能填充
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
                                //子類覆蓋方法作額外處理
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
                                //激活各類BeanFactory處理器
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
                                //註冊BeanBeanPostProcessor
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
                                //爲上下文初始化message源,即不一樣語言的消息體,國際化處理.
				initMessageSource();

				// Initialize event multicaster for this context.
                                //初始化應用消息廣播器
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
                                //留給子類初始化其餘bean
				onRefresh();

				// Check for listener beans and register them.
                                //在全部註冊的bean中查找Listener bean,註冊到消息廣播器中
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
                                //初始化剩下的單利bean(非惰性)
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
                               //完成刷新,通知生命週期處理器,同時發出ContextRefreshEvent 通知別人
				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();
			}
		}
	}

二 prepareBeanFactory 方法源碼分析java

/**
	 * Configure the factory's standard context characteristics,
	 * such as the context's ClassLoader and post-processors.
	 * @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的classloader爲當前context的classLoader
		beanFactory.setBeanClassLoader(getClassLoader());
                //設置beanFactory的表達式語言處理器,spring3增長了表達式語言的支持
		beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
                //爲beanfactory增長了一個默認的propertyEditor,這個主要針對bean的屬性等設置管理的一個工具
		beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

		// Configure the bean factory with context callbacks.
                //添加BeanPostProcessor
		beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
                //設置須要忽略自動配置接口
		beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
		beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
		beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
		beanFactory.ignoreDependencyInterface(EnvironmentAware.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);

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

個人博客即將同步至騰訊雲+社區,邀請你們一同入駐:https://cloud.tencent.com/developer/support-plan?invite_code=2okgifrej9ussspring

相關文章
相關標籤/搜索