Spring 原始碼閱讀(二)IoC 容器初始化以及 BeanFactory 建立和 BeanDefinition 載入過程

LinweiWang發表於2024-04-22

相關程式碼提交記錄:https://github.com/linweiwang/spring-framework-5.3.33

IoC 容器三種啟動方式

XML

JavaSE:

ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml")
ApplicationContext context = new FileSystemXmlApplicationContext("C:/beans.xml")

JavaWeb

透過 web.xml 配置 ContextLoaderListener,指定 Spring 配置檔案。

XML+註解

因為有 XML ,所以和純 XML 啟動方式一樣

註解

JavaSE

ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class)

JavaWeb

透過 web.xml 配置 ContextLoaderListener,指定 Spring 配置檔案。

BeanFactory 是 Spring 框架中 IoC 容器的頂層接⼝,它只是⽤來定義⼀些基礎功能,定義⼀些基礎規範,⽽ ApplicationContext 是它的⼀個⼦接⼝,所以 ApplicationContext 是具備 BeanFactory 提供的全部功能力的。
通常,我們稱 BeanFactory 為 SpringIOC 的基礎容器,ApplicationContext 是容器的⾼級接⼝,⽐
BeanFactory 要擁有更多的功能,⽐如說國際化⽀持和資源訪問(XML、Java 配置類)等等。

image

下面以純 XML 依賴原有 spring-research 來跟蹤原始碼。

IoC 容器初始化主體流程

分析 new ClassPathXmlApplicationContext("spring-config.xml");

ClassPathXmlApplicationContext.java

    // 建立 ClassPathXmlApplicationContext,載入 XML 中的定義資訊,並且自動 refresh 容器(Context)
	public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
		// 呼叫過載方法
		this(new String[] {configLocation}, true, null);
	}

	public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {

		// 初始化父類
		super(parent);
		// 設定配置檔案
		setConfigLocations(configLocations);
		// refresh context
		if (refresh) {
			refresh();
		}
	}

進入 refresh() 方法,在父類 AbstractApplicationContext 中

	@Override
	public void refresh() throws BeansException, IllegalStateException {
		// 物件鎖
		synchronized (this.startupShutdownMonitor) {
			StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");

			// 重新整理前的預處理
			// Prepare this context for refreshing.
			prepareRefresh();

			// 獲取 BeanFactory: 預設實現是 DefaultListableBeanFactory
			// 載入 BeanDefinition 並註冊到 BeanDefinitionRegistry
			// Tell the subclass to refresh the internal bean factory.
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// BeanFactory 預準備工作
			// Prepare the bean factory for use in this context.
			prepareBeanFactory(beanFactory);

			try {
				// BeanFactory 準備工作完成後的後置處理,留給子類實現
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
				// 例項化實現了 BeanFactoryPostProcessor 介面的 Bean,並呼叫該介面方法
				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);
				// 註冊 BeanPostProcessor (Bean 的後置處理器),在建立 Bean 的前後執行
				// Register bean processors that intercept bean creation.
				registerBeanPostProcessors(beanFactory);
				beanPostProcess.end();

				// 初始化 MessageSource 元件:國際化、訊息繫結、訊息解析等
				// Initialize message source for this context.
				initMessageSource();

				// 初始化事件派發器
				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// 初始化其他特殊的 Bean,在容器重新整理的時候子類自定義實現:如建立 Tomcat、Jetty 等 Web 伺服器
				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// 註冊應用監聽器(即實現了 ApplicationListener 介面的 Bean)
				// Check for listener beans and register them.
				registerListeners();

				// 初始化建立非懶載入的單例 Bean、填充屬性、呼叫初始化方法( afterPropertiesSet,init-method 等)、呼叫 BeanPostProcessor 後置處理器
				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// 完成 context 重新整理,呼叫 LifecycleProcessor 的 onRefresh 方法併發布 ContextRefreshedEvent
				// Last step: publish corresponding event.
				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();
				contextRefresh.end();
			}
		}
	}

整體流程如下:

1 重新整理前的預處理: prepareRefresh();
主要是一些準備工作設定其啟動日期和活動標誌以及執行一些屬性的初始化。

2 初始化 BeanFactory: obtainFreshBeanFactory();

  • 如果有舊的 BeanFactory 就刪除並建立新的 BeanFactory
  • 解析所有的 Spring 配置檔案,將配置檔案中定義的 bean 封裝成 BeanDefinition,載入到BeanFactory 中(這裡只註冊,不會進行 Bean 的例項化)

3 BeanFactory 預準備工作:prepareBeanFactory(beanFactory);
配置 BeanFactory 的標準上下文特徵,例如上下文的 ClassLoader、後置處理器等。

4 BeanFactory 準備工作完成後的後置處理,留給子類實現:postProcessBeanFactory(beanFactory);
空方法,如果子類需要,自己去實現

5 呼叫 Bean 工廠後置處理器:invokeBeanFactoryPostProcessors(beanFactory);

例項化和呼叫所有BeanFactoryPostProcessor,完成類的掃描、解析和註冊。
BeanFactoryPostProcessor 介面是 Spring 初始化 BeanFactory 時對外暴露的擴充套件點,Spring IoC 容器允許 BeanFactoryPostProcessor 在容器例項化任何 bean 之前讀取 bean 的定義,並可以修改它。

6 註冊 BeanPostProcesso:registerBeanPostProcessors(beanFactory);
所有實現了 BeanPostProcessor 介面的類註冊到 BeanFactory 中。

7 初始化 MessageSource 元件:initMessageSource();
初始化MessageSource元件(做國際化功能;訊息繫結,訊息解析)

8 初始化事件派發器:initApplicationEventMulticaster();
初始化應用的事件派發/廣播器 ApplicationEventMulticaster。

9 初始化其他特殊的 Bean:onRefresh();
空方法,模板設計模式;子類重寫該方法並在容器重新整理的時候自定義邏輯。
例:SpringBoot 在 onRefresh() 完成內建 Tomcat 的建立及啟動

10 註冊應用監聽器:registerListeners();
向事件分發器註冊硬編碼設定的 ApplicationListener,向事件分發器註冊一個 IoC 中的事件監聽器(並不例項化)

11 初始化建立非懶載入的單例 Bean:finishBeanFactoryInitialization(beanFactory);
初始化建立非懶載入的單例 Bean、填充屬性、呼叫初始化方法( afterPropertiesSet,init-method 等)、呼叫 BeanPostProcessor 後置處理器,是整個 Spring IoC 核心中的核心。

12 完成 context 重新整理:finishRefresh();
完成 context 重新整理,呼叫 LifecycleProcessor 的 onRefresh 方法併發布 ContextRefreshedEvent

獲取 BeanFactory 子流程

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

AbstractApplicationContext.java

	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		// 對 BeanFactory 進行重新整理操作,預設實現 AbstractRefreshableApplicationContext#refreshBeanFactory
		refreshBeanFactory();
		// 返回上一步 beanFactory,預設實現 AbstractRefreshableApplicationContext#getBeanFactory
		return getBeanFactory();
	}

AbstractRefreshableApplicationContext

	@Override
	protected final void refreshBeanFactory() throws BeansException {
		// 判斷是否已有 BeanFactory
		if (hasBeanFactory()) {
			// 銷燬 Bean
			destroyBeans();
			// 關閉 BeanFactory
			closeBeanFactory();
		}
		try {
			// 例項化 DefaultListableBeanFactory
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			// 設定序列化 ID
			beanFactory.setSerializationId(getId());
			// 自定義 BeanFactory 的一些屬性:allowBeanDefinitionOverriding、allowCircularReferences
			//   allowBeanDefinitionOverriding 是否允許覆蓋
			//   allowCircularReferences  是否允許迴圈依賴
			customizeBeanFactory(beanFactory);
			// 載入應用中的 BeanFactory
			loadBeanDefinitions(beanFactory);
			// 賦值給當前 beanFactory 屬性
			this.beanFactory = beanFactory;
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}

	@Override
	public final ConfigurableListableBeanFactory getBeanFactory() {
		DefaultListableBeanFactory beanFactory = this.beanFactory;
		if (beanFactory == null) {
			throw new IllegalStateException("BeanFactory not initialized or already closed - " +
					"call 'refresh' before accessing beans via the ApplicationContext");
		}
		return beanFactory;
	}

image

BeanDefinition 載入解析及註冊子流程

繼續分析 AbstractRefreshableApplicationContext#refreshBeanFactory 中的 loadBeanDefinitions 的實現方法在 AbstractXmlApplicationContext#loadBeanDefinitions 中(若是註解在 AnnotationConfigWebApplicationContext)

AbstractXmlApplicationContext

	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// 給指定的 BeanFactory 建立一個 XmlBeanDefinitionReader 進行讀取和解析 XML
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// 給 XmlBeanDefinitionReader 設定上下文資訊
		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setEnvironment(getEnvironment());
		beanDefinitionReader.setResourceLoader(this);
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// 提供給子類上西安的模板方法:自定義初始化策略
		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		initBeanDefinitionReader(beanDefinitionReader);
		// 真正的去載入 BeanDefinitions
		loadBeanDefinitions(beanDefinitionReader);
	}

	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		// 從 Resource 資源物件載入 BeanDefinitions
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			reader.loadBeanDefinitions(configResources);
		}
		// 從 XML 配置檔案載入 BeanDefinition 物件
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			reader.loadBeanDefinitions(configLocations);
		}
	}

reader.loadBeanDefinitions(configLocations); 中呼叫了 AbstractBeanDefinitionReader#loadBeanDefinitions

	@Override
	public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
		Assert.notNull(locations, "Location array must not be null");
		int count = 0;
		// 如果有多個配置檔案,迴圈讀取載入,並統計數量
		for (String location : locations) {
			count += loadBeanDefinitions(location);
		}
		return count;
	}

	@Override
	public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(location, null);
	}

	public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
		// 獲取上下文的 ResourceLoader (資源載入器)
		ResourceLoader resourceLoader = getResourceLoader();
		if (resourceLoader == null) {
			throw new BeanDefinitionStoreException(
					"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
		}

		// 判斷資源載入器是否為 ResourcePatternResolver 型別
		if (resourceLoader instanceof ResourcePatternResolver) {
			// Resource pattern matching available.
			try {
				// 統一載入轉換為 Resource 物件
				Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
				// 透過 Resource 物件載入 BeanDefinitions
				int count = loadBeanDefinitions(resources);
				if (actualResources != null) {
					Collections.addAll(actualResources, resources);
				}
				if (logger.isTraceEnabled()) {
					logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
				}
				return count;
			}
			catch (IOException ex) {
				throw new BeanDefinitionStoreException(
						"Could not resolve bean definition resource pattern [" + location + "]", ex);
			}
		}
		else {
    		// 否則以絕對路徑轉換為 Resource 物件
			// Can only load single resources by absolute URL.
			Resource resource = resourceLoader.getResource(location);
			int count = loadBeanDefinitions(resource);
			if (actualResources != null) {
				actualResources.add(resource);
			}
			if (logger.isTraceEnabled()) {
				logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
			}
			return count;
		}
	}

	@Override
	public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		Assert.notNull(resources, "Resource array must not be null");
		int count = 0;
		for (Resource resource : resources) {
			count += loadBeanDefinitions(resource);
		}
		return count;
	}

	@Override
	public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
		Assert.notNull(resources, "Resource array must not be null");
		int count = 0;
		for (Resource resource : resources) {
			// 載入
			count += loadBeanDefinitions(resource);
		}
		return count;
	}

loadBeanDefinitions(resource); 呼叫了 XmlBeanDefinitionReader#loadBeanDefinitions 方法

	@Override
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(new EncodedResource(resource));
	}

	public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
		Assert.notNull(encodedResource, "EncodedResource must not be null");
		if (logger.isTraceEnabled()) {
			logger.trace("Loading XML bean definitions from " + encodedResource);
		}

		Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();

		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}

		try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
			// 把 XML 檔案流封裝為 InputSource 物件
			InputSource inputSource = new InputSource(inputStream);
			if (encodedResource.getEncoding() != null) {
				inputSource.setEncoding(encodedResource.getEncoding());
			}
			// 執行載入邏輯
			return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"IOException parsing XML document from " + encodedResource.getResource(), ex);
		}
		finally {
			currentResources.remove(encodedResource);
			if (currentResources.isEmpty()) {
				this.resourcesCurrentlyBeingLoaded.remove();
			}
		}
	}

	protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
			throws BeanDefinitionStoreException {

		try {
			// 讀取 XML 資訊,將 XML 中資訊儲存到 Document 物件中
			Document doc = doLoadDocument(inputSource, resource);
			// 再解析 Document 物件,封裝為 BeanDefinition 物件進行註冊
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
		catch (BeanDefinitionStoreException ex) {
			throw ex;
		}
		catch (SAXParseException ex) {
			throw new XmlBeanDefinitionStoreException(resource.getDescription(),
					"Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
		}
		catch (SAXException ex) {
			throw new XmlBeanDefinitionStoreException(resource.getDescription(),
					"XML document from " + resource + " is invalid", ex);
		}
		catch (ParserConfigurationException ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"Parser configuration exception parsing XML from " + resource, ex);
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"IOException parsing XML document from " + resource, ex);
		}
		catch (Throwable ex) {
			throw new BeanDefinitionStoreException(resource.getDescription(),
					"Unexpected exception parsing XML document from " + resource, ex);
		}
	}

	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		// 獲取已有 BeanDefinition 的數量
		int countBefore = getRegistry().getBeanDefinitionCount();
		// 註冊 BeanDefinition
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		// 計算出新註冊的 BeanDefinition 數量
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}

documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); 會進入 DefaultBeanDefinitionDocumentReader#registerBeanDefinitions

	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		this.readerContext = readerContext;
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}

	protected void doRegisterBeanDefinitions(Element root) {
		// Any nested <beans> elements will cause recursion in this method. In
		// order to propagate and preserve <beans> default-* attributes correctly,
		// keep track of the current (parent) delegate, which may be null. Create
		// the new (child) delegate with a reference to the parent for fallback purposes,
		// then ultimately reset this.delegate back to its original (parent) reference.
		// this behavior emulates a stack of delegates without actually necessitating one.
		BeanDefinitionParserDelegate parent = this.delegate;
		this.delegate = createDelegate(getReaderContext(), root, parent);

		if (this.delegate.isDefaultNamespace(root)) {
			String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
			if (StringUtils.hasText(profileSpec)) {
				String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
						profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
				// We cannot use Profiles.of(...) since profile expressions are not supported
				// in XML config. See SPR-12458 for details.
				if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
					if (logger.isDebugEnabled()) {
						logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
								"] not matching: " + getReaderContext().getResource());
					}
					return;
				}
			}
		}

		preProcessXml(root);
		// 真正解析 XML
		parseBeanDefinitions(root, this.delegate);
		postProcessXml(root);

		this.delegate = parent;
	}

	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		if (delegate.isDefaultNamespace(root)) {
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				if (node instanceof Element) {
					Element ele = (Element) node;
					if (delegate.isDefaultNamespace(ele)) {
						// 解析預設標籤元素:"import", "alias", "bean"
						parseDefaultElement(ele, delegate);
					}
					else {
						// 解析自定義標籤
						delegate.parseCustomElement(ele);
					}
				}
			}
		}
		else {
			// 解析自定義標籤
			delegate.parseCustomElement(root);
		}
	}

	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
		// import 標籤
		if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
			importBeanDefinitionResource(ele);
		}
		// alias 標籤
		else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
			processAliasRegistration(ele);
		}
		// bean 標籤:著重分析
		else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
			processBeanDefinition(ele, delegate);
		}
		// 巢狀 bean 標籤
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}

	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		// 解析 bean 標籤為 BeanDefinitionHolder 裡面持有 BeanDefinition
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			// 若有必要裝飾 bdHolder (bean 標籤內有自定義標籤的情況下)
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// 完成 BeanDefinition 的註冊
				// Register the final decorated instance.
				BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
			}
			catch (BeanDefinitionStoreException ex) {
				getReaderContext().error("Failed to register bean definition with name '" +
						bdHolder.getBeanName() + "'", ele, ex);
			}
			// Send registration event.
			getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
		}
	}

BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); 呼叫了 BeanDefinitionReaderUtils#registerBeanDefinition

	public static void registerBeanDefinition(
			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
			throws BeanDefinitionStoreException {

        // 註冊
		// Register bean definition under primary name.
		String beanName = definitionHolder.getBeanName();
		registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());

		// Register aliases for bean name, if any.
		String[] aliases = definitionHolder.getAliases();
		if (aliases != null) {
			for (String alias : aliases) {
				registry.registerAlias(beanName, alias);
			}
		}
	}

registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); 呼叫了 DefaultListableBeanFactory#registerBeanDefinition

	@Override
	public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
			throws BeanDefinitionStoreException {

		Assert.hasText(beanName, "Bean name must not be empty");
		Assert.notNull(beanDefinition, "BeanDefinition must not be null");

		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		if (existingDefinition != null) {
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			else if (existingDefinition.getRole() < beanDefinition.getRole()) {
				// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
				if (logger.isInfoEnabled()) {
					logger.info("Overriding user-defined bean definition for bean '" + beanName +
							"' with a framework-generated bean definition: replacing [" +
							existingDefinition + "] with [" + beanDefinition + "]");
				}
			}
			else if (!beanDefinition.equals(existingDefinition)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Overriding bean definition for bean '" + beanName +
							"' with a different definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			else {
				if (logger.isTraceEnabled()) {
					logger.trace("Overriding bean definition for bean '" + beanName +
							"' with an equivalent definition: replacing [" + existingDefinition +
							"] with [" + beanDefinition + "]");
				}
			}
			this.beanDefinitionMap.put(beanName, beanDefinition);
		}
		else {
			// 註冊邏輯
			if (hasBeanCreationStarted()) {
				// Cannot modify startup-time collection elements anymore (for stable iteration)
				synchronized (this.beanDefinitionMap) {
					this.beanDefinitionMap.put(beanName, beanDefinition);
					List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
					updatedDefinitions.addAll(this.beanDefinitionNames);
					updatedDefinitions.add(beanName);
					this.beanDefinitionNames = updatedDefinitions;
					removeManualSingletonName(beanName);
				}
			}
			else {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				removeManualSingletonName(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
		else if (isConfigurationFrozen()) {
			clearByTypeCache();
		}
	}

整體呼叫鏈如下

AbstractRefreshableApplicationContext#refreshBeanFactory
    AbstractXmlApplicationContext#loadBeanDefinitions
        AbstractBeanDefinitionReader#loadBeanDefinitions // 載入 BeanDefinition
            XmlBeanDefinitionReader#loadBeanDefinitions
                XmlBeanDefinitionReader#doLoadBeanDefinitions // 讀取 XML 為 Document
                    XmlBeanDefinitionReader#registerBeanDefinitions // 真正開始註冊
                        DefaultBeanDefinitionDocumentReader#registerBeanDefinitions
                            DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions
                                DefaultBeanDefinitionDocumentReader#parseBeanDefinitions
                                    DefaultBeanDefinitionDocumentReader#parseDefaultElement
                                        DefaultBeanDefinitionDocumentReader#processBeanDefinition
                                            BeanDefinitionReaderUtils#registerBeanDefinition
                                                DefaultListableBeanFactory#registerBeanDefinition

image

相關文章