徹底搞懂Bean載入

微笑面對生活發表於2019-01-08

0. Bean 載入原理

載入過程: 通過 ResourceLoader和其子類DefaultResourceLoader完成資原始檔位置定位,實現從類路徑,檔案系統,url等方式定位功能,完成定位後得到Resource物件,再交給BeanDefinitionReader,它再委託給BeanDefinitionParserDelegate完成bean的解析並得到BeanDefinition物件,然後通過registerBeanDefinition方法進行註冊,IOC容器內ibu維護了一個HashMap來儲存該BeanDefinition物件,Spring中的BeanDefinition其實就是我們用的JavaBean

什麼是BeanDefinition物件

BeanDefinition是一個介面,描述了一個bean例項,它具有屬性值,建構函式引數值以及具體實現提供的更多資訊。

徹底搞懂Bean載入

注重理解載入過程

在開始之前需要認真閱讀和理解這個過程,有了這個過程,閱讀原始碼難度就小了一半。

大多原始碼都進行了註釋,有的是官方英文註釋。中文是主線(本文也主要也是過一遍主線),想要面面俱到需要自己再去摸索。

1. bean.xml

一個普通的bean配置檔案,這裡我要強調的是它裡面的格式,因為解析標籤的時候會用到。它有<beans>``<bean>``<import>``<alias>等標籤,下文會對他們進行解析並翻譯成BeanDefinition物件。

<beans>

  <!-- this definition could be inside one beanRefFactory.xml file -->
  <bean id="a.qualified.name.of.some.sort"
      class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <property name="configLocation" value="org/springframework/web/context/beans1.xml"/>
  </bean>

  <!-- while the following two could be inside another, also on the classpath,
	perhaps coming from another component jar -->
  <bean id="another.qualified.name"
      class="org.springframework.context.support.ClassPathXmlApplicationContext">
    <property name="configLocation" value="org/springframework/web/context/beans1.xml"/>
    <property name="parent" ref="a.qualified.name.of.some.sort"/>
  </bean>

  <alias name="another.qualified.name" alias="a.qualified.name.which.is.an.alias"/>

</beans>
複製程式碼

2. ResourceLoader.java

載入資源的策略介面(策略模式)。 DefaultResourceLoader is a standalone implementation that is usable outside an ApplicationContext, also used by ResourceEditor

An ApplicationContext is required to provide this functionality, plus extended ResourcePatternResolver support.

public interface ResourceLoader {

	/** Pseudo URL prefix for loading from the class path: "classpath:". */
	String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;
       
        // 返回一個Resource 物件 (明確配置檔案位置的物件)
	Resource getResource(String location);

        // 返回ResourceLoader的ClassLoader
	@Nullable
	ClassLoader getClassLoader();
}
複製程式碼

然後我們看看DefaultResourceLoader對於getResource()方法的實現。

	public Resource getResource(String location) {
		Assert.notNull(location, "Location must not be null");

		for (ProtocolResolver protocolResolver : this.protocolResolvers) {
			Resource resource = protocolResolver.resolve(location, this);
			if (resource != null) {
				return resource;
			}
		}
               // 如果location 以 / 開頭
		if (location.startsWith("/")) {
			return getResourceByPath(location);
		}
                // 如果location 以classpath: 開頭
		else if (location.startsWith(CLASSPATH_URL_PREFIX)) {
			return new ClassPathResource(location.substring(CLASSPATH_URL_PREFIX.length()), getClassLoader());
		}
		else {
			try {
				// Try to parse the location as a URL...
				URL url = new URL(location);
				return (ResourceUtils.isFileURL(url) ? new FileUrlResource(url) : new UrlResource(url));
			}
			catch (MalformedURLException ex) {
				// No URL -> resolve as resource path.
				return getResourceByPath(location);
			}
		}
	}
複製程式碼

可以看到,它判斷了三種情況:/ classpath: url格式匹配, 然後呼叫相對應的處理方法,我只分析classpath:,因為這是最常用的。所以看一看ClassPathResource實現:

	public ClassPathResource(String path, @Nullable ClassLoader classLoader) {
		Assert.notNull(path, "Path must not be null");
		String pathToUse = StringUtils.cleanPath(path);
		if (pathToUse.startsWith("/")) {
			pathToUse = pathToUse.substring(1);
		}
		this.path = pathToUse;
		this.classLoader = (classLoader != null ? classLoader : ClassUtils.getDefaultClassLoader());
	}
複製程式碼

看了上面的程式碼,意味著你配置靜態資原始檔路徑的時候,不用糾結classpath:後面用不用寫/,因為如果寫了它會給你過濾掉。

那url如何定位的呢?

跟蹤getResourceByPath(location)方法:

	@Override
	protected Resource getResourceByPath(String path) {
		if (path.startsWith("/")) {
			path = path.substring(1);
		}
		// 這裡使用檔案系統資源物件來定義bean檔案
		return new FileSystemResource(path);
	}
複製程式碼

好了,很明顯...跑偏了,因為我們想要的是xml檔案及路徑的解析,不過還好,換湯不換藥。下文中會涉及到。

觸發bean載入

回到正題,我們在使用spring手動載入bean.xml的時候,用到:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
複製程式碼

那就從ClassPathXmlApplicationContext類開始深入:

3. ClassPathXmlApplicationContext.java

這個類裡面只有構造方法(多個)和一個getConfigResources()方法,構造方法最終都統一打到下面這個構造方法中(介面卡模式):

	public ClassPathXmlApplicationContext(
			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
			throws BeansException {
	// 動態的確定用哪個載入器去載入 配置檔案
		1.super(parent);
	// 告訴讀取器 配置檔案在哪裡, 定位載入配置檔案
		2.setConfigLocations(configLocations);
	// 重新整理
		if (refresh) {
			// 在建立IOC容器前,如果容器已經存在,則需要把已有的容器摧毀和關閉,以保證refresh
			//之後使用的是新的IOC容器
			3.refresh();
		}
	}
複製程式碼

注意: 這個類非常關鍵,我認為它定義了一個xml載入bean的一個Life Cycle:

  1. super() 方法完成類載入器的指定。
  2. setConfigLocations(configLocations);方法對配置檔案進行定位和解析,拿到Resource物件。
  3. refresh();方法對標籤進行解析拿到BeanDefition物件,在通過校驗後將其註冊到IOC容器。(主要研究該方法)

我標記的1. 2. 3. 對應後面的方法x, 方便閱讀。

先深入瞭解下setConfigLocations(configLocations);方法:

方法2. setConfigLocations(configLocations)
	// 解析Bean定義資原始檔的路徑,處理多個資原始檔字串陣列
	public void setConfigLocations(@Nullable String... locations) {
		if (locations != null) {
			Assert.noNullElements(locations, "Config locations must not be null");
			this.configLocations = new String[locations.length];
			for (int i = 0; i < locations.length; i++) {
				// resolvePath 為同一個類中將字串解析為路徑的方法
				this.configLocations[i] = resolvePath(locations[i]).trim();
			}
		}
		else {
			this.configLocations = null;
		}
	}
複製程式碼

然後我們繼續上面看ClassPathXmlApplicationContextrefresh()方法:

方法3. refresh()
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// 為refresh 準備上下文
			prepareRefresh();

			// 通知子類去重新整理 Bean工廠
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// 用該上下文來 準備bean工廠
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				invokeBeanFactoryPostProcessors(beanFactory);

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

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				finishBeanFactoryInitialization(beanFactory);

				// 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();
			}
		}
	}
複製程式碼

**注:**下面的方法全都是圍繞refresh()裡深入閱讀,該方法套的很深,下面的閱讀可能會引起不適。

然後看看refresh()方法中的obtainFreshBeanFactory()方法:

方法3.1 obtainFreshBeanFactory()
	// 呼叫--重新整理bean工廠
	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
		// 委派模式:父類定義了refreshBeanFactory方法,具體實現呼叫子類容器
		refreshBeanFactory();
		return getBeanFactory();
	}
複製程式碼

然後看obtainFreshBeanFactory()refreshBeanFactory()方法

方法3.1.1 refreshBeanFactory()
       // 重新整理bean工廠
	protected final void refreshBeanFactory() throws BeansException {
		// 如果存在容器,就先銷燬並關閉
		if (hasBeanFactory()) {
			destroyBeans();
			closeBeanFactory();
		}
		try {
			// 建立IOC容器
			DefaultListableBeanFactory beanFactory = createBeanFactory();
			beanFactory.setSerializationId(getId());
			// 對容器進行初始化
			customizeBeanFactory(beanFactory);
			// 呼叫載入Bean定義的方法,(使用了委派模式)
			loadBeanDefinitions(beanFactory);
			synchronized (this.beanFactoryMonitor) {
				this.beanFactory = beanFactory;
			}
		}
		catch (IOException ex) {
			throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
		}
	}
複製程式碼

然後再跟進refreshBeanFactory()loadBeanDefinitions()方法:

方法3.1.1.1 loadBeanDefinitions()

通過 XmlBeanDefinitionReader 載入 BeanDefinition

	// 通過 XmlBeanDefinitionReader 載入 BeanDefinition
	@Override
	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
		// Create a new XmlBeanDefinitionReader for the given BeanFactory.
		// 為beanFactory 建立一個新的 XmlBeanDefinitionReader
		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);

		// Configure the bean definition reader with this context's
		// resource loading environment.
		beanDefinitionReader.setEnvironment(this.getEnvironment());
		// 為 Bean讀取器設定Spring資源載入器 (因為祖父類是ResourceLoader的子類,所以也是ResourceLoader)
		beanDefinitionReader.setResourceLoader(this);
		//  為 Bean讀取器設定SAX xml解析器DOM4J
		beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));

		// Allow a subclass to provide custom initialization of the reader,
		// then proceed with actually loading the bean definitions.
		// 初始化 BeanDefinition讀取器
		initBeanDefinitionReader(beanDefinitionReader);
		// 真正載入 bean定義
		loadBeanDefinitions(beanDefinitionReader);
	}
複製程式碼

再跟進loadBeanDefinitions(DefaultListableBeanFactory beanFactory)方法中的loadBeanDefinitions(XmlBeanDefinitionReader reader)方法:

方法3.1.1.1.1 loadBeanDefinitions()

XMLBean讀取器載入BeanDefinition 資源

	// XMLBean讀取器載入Bean 定義資源
	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
		// 獲取Bean定義資源的定位
		Resource[] configResources = getConfigResources();
		if (configResources != null) {
			// XMLBean讀取器呼叫其父類 AbstractBeanDefinitionReader 讀取定位的Bean定義資源
			reader.loadBeanDefinitions(configResources);
		}
		// 如果子類中獲取的bean定義資源定位為空,
		// 則獲取 FileSystemXmlApplicationContext構造方法中 setConfigLocations 方法設定的資源
		String[] configLocations = getConfigLocations();
		if (configLocations != null) {
			// XMLBean讀取器呼叫其父類 AbstractBeanDefinitionReader 讀取定位的Bean定義資源
			reader.loadBeanDefinitions(configLocations);
		}
	}
複製程式碼
	@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(): 這只是一個抽象方法,找到XmlBeanDefinitionReader子類的實現:

	@Override
	public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
		return loadBeanDefinitions(new EncodedResource(resource));
	}
複製程式碼

再深入loadBeanDefinitions:

通過明確的xml檔案載入bean

    // 通過明確的xml檔案載入bean
	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 == null) {
			currentResources = new HashSet<>(4);
			this.resourcesCurrentlyBeingLoaded.set(currentResources);
		}
		if (!currentResources.add(encodedResource)) {
			throw new BeanDefinitionStoreException(
					"Detected cyclic loading of " + encodedResource + " - check your import definitions!");
		}
		try {
			// 將資原始檔轉為InputStream的IO流
			InputStream inputStream = encodedResource.getResource().getInputStream();
			try {
				// 從流中獲取 xml解析資源
				InputSource inputSource = new InputSource(inputStream);
				if (encodedResource.getEncoding() != null) {
					// 設定編碼
					inputSource.setEncoding(encodedResource.getEncoding());
				}
				// 具體的讀取過程
				return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
			}
			finally {
				inputStream.close();
			}
		}
		catch (IOException ex) {
			throw new BeanDefinitionStoreException(
					"IOException parsing XML document from " + encodedResource.getResource(), ex);
		}
		finally {
			currentResources.remove(encodedResource);
			if (currentResources.isEmpty()) {
				this.resourcesCurrentlyBeingLoaded.remove();
			}
		}
	}
複製程式碼

再深入到doLoadBeanDefinitions():

真正開始載入 BeanDefinitions

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

		try {
			// 將xml 檔案轉換為DOM物件
			Document doc = doLoadDocument(inputSource, resource);
			// 對bean定義解析的過程,該過程會用到 Spring的bean配置規則
			int count = registerBeanDefinitions(doc, resource);
			if (logger.isDebugEnabled()) {
				logger.debug("Loaded " + count + " bean definitions from " + resource);
			}
			return count;
		}
        ...  ...  ..
}
複製程式碼

doLoadDocument()方法將流進行解析,返回一個Document物件:return builder.parse(inputSource);為了避免擾亂思路,這裡的深入自己去完成。

還需要再深入到:registerBeanDefinitions()

註冊 BeanDefinitions

	public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
		// 得到容器中註冊的bean數量
		int countBefore = getRegistry().getBeanDefinitionCount();
		// 解析過程入口,這裡使用了委派模式
		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
		// 統計解析的bean數量
		return getRegistry().getBeanDefinitionCount() - countBefore;
	}
複製程式碼

再深入registerBeanDefinitions()方法(該方法是委派模式的結果):

	@Override
	public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
		// 獲得XML描述符
		this.readerContext = readerContext;
		doRegisterBeanDefinitions(doc.getDocumentElement());
	}
複製程式碼

再深入doRegisterBeanDefinitions(doc.getDocumentElement());

真正開始註冊 BeanDefinitions :

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

		// 在bean解析定義之前,進行自定義解析,看是否是使用者自定義標籤
		preProcessXml(root);
		// 開始進行解析bean定義的document物件
		parseBeanDefinitions(root, this.delegate);
		// 解析bean定義之後,進行自定義的解析,增加解析過程的可擴充套件性
		postProcessXml(root);

		this.delegate = parent;
	}
複製程式碼

接下來看parseBeanDefinitions(root, this.delegate);:

document的根元素開始進行解析翻譯成BeanDefinitions

	// 從document的根元素開始進行解析翻譯成BeanDefinitions
	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
		// bean定義的document物件使用了spring預設的xml名稱空間
		if (delegate.isDefaultNamespace(root)) {
			// 獲取bean定義的document物件根元素的所有位元組點
			NodeList nl = root.getChildNodes();
			for (int i = 0; i < nl.getLength(); i++) {
				Node node = nl.item(i);
				// 獲得document節點是xml元素節點
				if (node instanceof Element) {
					Element ele = (Element) node;
					// bean定義的document的元素節點使用的是spring預設的xml名稱空間
					if (delegate.isDefaultNamespace(ele)) {
						// 使用spring的bean規則解析元素 節點
						parseDefaultElement(ele, delegate);
					}
					else {
						// 沒有使用spring預設的xml名稱空間,則使用使用者自定義的解析規則解析元素節點
						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);
		}
		// beans
		else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
			// recurse
			doRegisterBeanDefinitions(ele);
		}
	}
複製程式碼

importBeanDefinitionResource(ele);``processAliasRegistration(ele);``processBeanDefinition(ele, delegate);這三個方法裡分別展示了標籤解析的詳細過程。 這下看到了,它其實使用DOM4J來解析import bean alias等標籤,然後遞迴標籤內部直到拿到所有屬性並封裝到BeanDefition物件中。比如說processBeanDefinition方法:

給我一個element 解析成 BeanDefinition

	// 給我一個element 解析成 BeanDefinition
	protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
		// 真正解析過程
		BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
		if (bdHolder != null) {
			bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
			try {
				// Register the final decorated instance.
				// 註冊: 將db註冊到ioc,委託模式
				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));
		}
	}
複製程式碼

繼續深入registerBeanDefinition():

註冊BeanDefinitions 到 bean 工廠

	// 註冊BeanDefinitions 到 bean 工廠
	// definitionHolder : bean定義,包含了 name和aliases
	// registry: 註冊到的bean工廠
	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());

註冊BeanDefinitions 到IOC容器

注意:該方法所在類是介面,我們檢視的是DefaultListableBeanFactory.java所實現的該方法。

	// 實現BeanDefinitionRegistry介面,註冊BeanDefinitions 
	@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");

		// 校驗是否是 AbstractBeanDefinition)
		if (beanDefinition instanceof AbstractBeanDefinition) {
			try {
				// 標記 beanDefinition 生效
				((AbstractBeanDefinition) beanDefinition).validate();
			}
			catch (BeanDefinitionValidationException ex) {
				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
						"Validation of bean definition failed", ex);
			}
		}

		// 判斷beanDefinitionMap 裡是否已經有這個bean
		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
		//如果沒有這個bean
		if (existingDefinition != null) {
			//如果不允許bd 覆蓋已註冊的bean, 就丟擲異常
			if (!isAllowBeanDefinitionOverriding()) {
				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
			}
			// 如果允許覆蓋, 則同名的bean, 註冊的覆蓋先註冊的
			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 + "]");
				}
			}
			// 註冊到容器,beanDefinitionMap 就是個容器
			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;
					if (this.manualSingletonNames.contains(beanName)) {
						Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
						updatedSingletons.remove(beanName);
						this.manualSingletonNames = updatedSingletons;
					}
				}
			}
			else {
				// Still in startup registration phase
				this.beanDefinitionMap.put(beanName, beanDefinition);
				this.beanDefinitionNames.add(beanName);
				this.manualSingletonNames.remove(beanName);
			}
			this.frozenBeanDefinitionNames = null;
		}

		if (existingDefinition != null || containsSingleton(beanName)) {
			resetBeanDefinition(beanName);
		}
	}
複製程式碼

這個方法中對所需要載入的bean進行校驗,沒有問題的話就putbeanDefinitionMap中,beanDefinitionMap其實就是IOC.這樣我們的Bean就被載入到IOC容器中了。



如果你喜歡我的文章,那麻煩請關注我的公眾號PlayInJava,公眾號重點分析架構師技術,該公眾號還處於初始階段,謝謝大家的支援。

徹底搞懂Bean載入
關注公眾號,回覆java架構獲取架構視訊資源(後期還會分享不同的優質資源噢)。



相關文章