BeanDe" />

日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當(dāng)前位置:首頁 > 科技  > 軟件

徹底搞懂Spring的Bean加載

來源: 責(zé)編: 時(shí)間:2023-09-28 10:04:42 376觀看
導(dǎo)讀一、Bean 加載原理加載過程: 通過 ResourceLoader和其子類DefaultResourceLoader完成資源文件位置定位,實(shí)現(xiàn)從類路徑,文件系統(tǒng),url等方式定位功能,完成定位后得到Resource對(duì)象,再交給BeanDefinitionReader,它再委托給
BeanDe

QBM28資訊網(wǎng)——每日最新資訊28at.com

一、Bean 加載原理

加載過程: 通過 ResourceLoader和其子類DefaultResourceLoader完成資源文件位置定位,實(shí)現(xiàn)從類路徑,文件系統(tǒng),url等方式定位功能,完成定位后得到Resource對(duì)象,再交給BeanDefinitionReader,它再委托給
BeanDefinitionParserDelegate完成bean的解析并得到BeanDefinition對(duì)象,然后通過registerBeanDefinition方法進(jìn)行注冊(cè),IOC容器內(nèi)ibu維護(hù)了一個(gè)HashMap來保存該BeanDefinition對(duì)象,Spring中的BeanDefinition其實(shí)就是我們用的JavaBean。
QBM28資訊網(wǎng)——每日最新資訊28at.com

什么是BeanDefinition對(duì)象

BeanDefinition是一個(gè)接口,描述了一個(gè)bean實(shí)例,它具有屬性值,構(gòu)造函數(shù)參數(shù)值以及具體實(shí)現(xiàn)提供的更多信息。QBM28資訊網(wǎng)——每日最新資訊28at.com

在開始之前需要認(rèn)真閱讀和理解這個(gè)過程,有了這個(gè)過程,閱讀源碼難度就小了一半。QBM28資訊網(wǎng)——每日最新資訊28at.com

大多源碼都進(jìn)行了注釋,有的是官方英文注釋。QBM28資訊網(wǎng)——每日最新資訊28at.com

二、bean.xml

一個(gè)普通的bean配置文件,這里我要強(qiáng)調(diào)的是它里面的格式,因?yàn)榻馕鰳?biāo)簽的時(shí)候會(huì)用到。它有<beans>``<bean>``<import>``<alias>等標(biāo)簽,下文會(huì)對(duì)他們進(jìn)行解析并翻譯成BeanDefinition對(duì)象。QBM28資訊網(wǎng)——每日最新資訊28at.com

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

三、ResourceLoader.java

加載資源的策略接口(策略模式)。
DefaultResourceLoader is a standalone implementation that is usable outside an ApplicationContext, also used by ResourceEditorQBM28資訊網(wǎng)——每日最新資訊28at.com

An ApplicationContext is required to provide this functionality, plus extended ResourcePatternResolver support.QBM28資訊網(wǎng)——每日最新資訊28at.com

public interface ResourceLoader {	/** Pseudo URL prefix for loading from the class path: "classpath:". */	String CLASSPATH_URL_PREFIX = ResourceUtils.CLASSPATH_URL_PREFIX;               // 返回一個(gè)Resource 對(duì)象 (明確配置文件位置的對(duì)象)	Resource getResource(String location);        // 返回ResourceLoader的ClassLoader	@Nullable	ClassLoader getClassLoader();}

然后我們看看DefaultResourceLoader對(duì)于getResource()方法的實(shí)現(xiàn)。QBM28資訊網(wǎng)——每日最新資訊28at.com

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格式匹配, 然后調(diào)用相對(duì)應(yīng)的處理方法,我只分析classpath:,因?yàn)檫@是最常用的。所以看一看ClassPathResource實(shí)現(xiàn):QBM28資訊網(wǎng)——每日最新資訊28at.com

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

看了上面的代碼,意味著你配置靜態(tài)資源文件路徑的時(shí)候,不用糾結(jié)classpath:后面用不用寫/,因?yàn)槿绻麑懥怂鼤?huì)給你過濾掉。QBM28資訊網(wǎng)——每日最新資訊28at.com

那url如何定位的呢?QBM28資訊網(wǎng)——每日最新資訊28at.com

跟蹤getResourceByPath(location)方法:QBM28資訊網(wǎng)——每日最新資訊28at.com

@Override	protected Resource getResourceByPath(String path) {		if (path.startsWith("/")) {			path = path.substring(1);		}		// 這里使用文件系統(tǒng)資源對(duì)象來定義bean文件		return new FileSystemResource(path);	}

好了,很明顯…跑偏了,因?yàn)槲覀兿胍氖莤ml文件及路徑的解析,不過還好,換湯不換藥。下文中會(huì)涉及到。QBM28資訊網(wǎng)——每日最新資訊28at.com

觸發(fā)bean加載

回到正題,我們?cè)谑褂胹pring手動(dòng)加載bean.xml的時(shí)候,用到:QBM28資訊網(wǎng)——每日最新資訊28at.com

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");

那就從ClassPathXmlApplicationContext開始:QBM28資訊網(wǎng)——每日最新資訊28at.com

四、ClassPathXmlApplicationContext.java

這個(gè)類里面只有構(gòu)造方法(多個(gè))和一個(gè)getConfigResources()方法,構(gòu)造方法最終都統(tǒng)一打到下面這個(gè)構(gòu)造方法中(Spring源碼經(jīng)常這樣,適配器模式):QBM28資訊網(wǎng)——每日最新資訊28at.com

public ClassPathXmlApplicationContext(			String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)			throws BeansException {	// 動(dòng)態(tài)的確定用哪個(gè)加載器去加載 配置文件		1.super(parent);	// 告訴讀取器 配置文件在哪里, 定位加載配置文件		2.setConfigLocations(configLocations);	// 刷新		if (refresh) {			// 在創(chuàng)建IOC容器前,如果容器已經(jīng)存在,則需要把已有的容器摧毀和關(guān)閉,以保證refresh			//之后使用的是新的IOC容器			3.refresh();		}	}

注意: 這個(gè)類非常關(guān)鍵,我認(rèn)為它定義了一個(gè)xml加載bean的一個(gè)Life Cycle:QBM28資訊網(wǎng)——每日最新資訊28at.com

  • super() 方法完成類加載器的指定。
  • setConfigLocations(configLocations);方法對(duì)配置文件進(jìn)行定位和解析,拿到Resource對(duì)象。
  • refresh();方法對(duì)標(biāo)簽進(jìn)行解析拿到BeanDefition對(duì)象,在通過校驗(yàn)后將其注冊(cè)到IOC容器。(主要研究該方法)

我標(biāo)記的1. 2. 3. 對(duì)應(yīng)后面的方法x, 方便閱讀。QBM28資訊網(wǎng)——每日最新資訊28at.com

先深入了解下setConfigLocations(configLocations);方法:QBM28資訊網(wǎng)——每日最新資訊28at.com

方法2. setConfigLocations()

// 解析Bean定義資源文件的路徑,處理多個(gè)資源文件字符串?dāng)?shù)組	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 為同一個(gè)類中將字符串解析為路徑的方法				this.configLocations[i] = resolvePath(locations[i]).trim();			}		}		else {			this.configLocations = null;		}	}

然后我們繼續(xù)上面看ClassPathXmlApplicationContext的refresh()方法:QBM28資訊網(wǎng)——每日最新資訊28at.com

方法3. refresh()

public void refresh() throws BeansException, IllegalStateException {		synchronized (this.startupShutdownMonitor) {			// 為refresh 準(zhǔn)備上下文			prepareRefresh();			// 通知子類去刷新 Bean工廠			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();			// 用該 上下文來 準(zhǔn)備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()里深入閱讀,該方法套的很深,下面的閱讀可能會(huì)引起不適。QBM28資訊網(wǎng)——每日最新資訊28at.com

然后看看refresh()方法中的obtainFreshBeanFactory()方法。QBM28資訊網(wǎng)——每日最新資訊28at.com

方法3.1 obtainFreshBeanFactory()

// 調(diào)用--刷新bean工廠	protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {		// 委派模式:父類定義了refreshBeanFactory方法,具體實(shí)現(xiàn)調(diào)用子類容器		refreshBeanFactory();		return getBeanFactory();	}

然后看obtainFreshBeanFactory()的 refreshBeanFactory()方法。QBM28資訊網(wǎng)——每日最新資訊28at.com

方法3.1.1 refreshBeanFactory()

// 刷新bean工廠	protected final void refreshBeanFactory() throws BeansException {		// 如果存在容器,就先銷毀并關(guān)閉		if (hasBeanFactory()) {			destroyBeans();			closeBeanFactory();		}		try {			// 創(chuàng)建IOC容器			DefaultListableBeanFactory beanFactory = createBeanFactory();			beanFactory.setSerializationId(getId());			// 對(duì)容器進(jìn)行初始化			customizeBeanFactory(beanFactory);			// 調(diào)用載入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);		}	}

然后再跟進(jìn)refreshBeanFactory() 的loadBeanDefinitions()方法。QBM28資訊網(wǎng)——每日最新資訊28at.com

方法3.1.1.1 loadBeanDefinitions()

通過 XmlBeanDefinitionReader 加載 BeanDefinition。QBM28資訊網(wǎng)——每日最新資訊28at.com

// 通過 XmlBeanDefinitionReader 加載 BeanDefinition	@Override	protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {		// Create a new XmlBeanDefinitionReader for the given BeanFactory.		// 為beanFactory 創(chuàng)建一個(gè)新的 XmlBeanDefinitionReader		XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);		// Configure the bean definition reader with this context's		// resource loading environment.		beanDefinitionReader.setEnvironment(this.getEnvironment());		// 為 Bean讀取器設(shè)置Spring資源加載器 (因?yàn)樽娓割愂荝esourceLoader的子類,所以也是ResourceLoader)		beanDefinitionReader.setResourceLoader(this);		//  為 Bean讀取器設(shè)置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);	}

再跟進(jìn)loadBeanDefinitions(DefaultListableBeanFactory beanFactory)方法中的loadBeanDefinitions(XmlBeanDefinitionReader reader)方法。QBM28資訊網(wǎng)——每日最新資訊28at.com

方法3.1.1.1.1 loadBeanDefinitions()

XMLBean讀取器加載BeanDefinition 資源。QBM28資訊網(wǎng)——每日最新資訊28at.com

// XMLBean讀取器加載Bean 定義資源	protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {		// 獲取Bean定義資源的定位		Resource[] configResources = getConfigResources();		if (configResources != null) {			// XMLBean讀取器調(diào)用其父類 AbstractBeanDefinitionReader 讀取定位的Bean定義資源			reader.loadBeanDefinitions(configResources);		}		// 如果子類中獲取的bean定義資源定位為空,		// 則獲取 FileSystemXmlApplicationContext構(gòu)造方法中 setConfigLocations 方法設(shè)置的資源		String[] configLocations = getConfigLocations();		if (configLocations != null) {			// XMLBean讀取器調(diào)用其父類 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(): 這只是一個(gè)抽象方法,找到XmlBeanDefinitionReader子類的實(shí)現(xiàn):QBM28資訊網(wǎng)——每日最新資訊28at.com

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

再深入loadBeanDefinitions:QBM28資訊網(wǎng)——每日最新資訊28at.com

通過明確的xml文件加載beanQBM28資訊網(wǎng)——每日最新資訊28at.com

// 通過明確的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 {			// 將資源文件轉(zhuǎn)為InputStream的IO流			InputStream inputStream = encodedResource.getResource().getInputStream();			try {				// 從流中獲取 xml解析資源				InputSource inputSource = new InputSource(inputStream);				if (encodedResource.getEncoding() != null) {					// 設(shè)置編碼					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():QBM28資訊網(wǎng)——每日最新資訊28at.com

真正開始加載 BeanDefinitions。QBM28資訊網(wǎng)——每日最新資訊28at.com

protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)			throws BeanDefinitionStoreException {		try {			// 將xml 文件轉(zhuǎn)換為DOM對(duì)象			Document doc = doLoadDocument(inputSource, resource);			// 對(duì)bean定義解析的過程,該過程會(huì)用到 Spring的bean配置規(guī)則			int count = registerBeanDefinitions(doc, resource);			if (logger.isDebugEnabled()) {				logger.debug("Loaded " + count + " bean definitions from " + resource);			}			return count;		}        ...  ...  ..}

doLoadDocument()方法將流進(jìn)行解析,返回一個(gè)Document對(duì)象:return builder.parse(inputSource);為了避免擾亂思路,這里的深入自己去完成。QBM28資訊網(wǎng)——每日最新資訊28at.com

還需要再深入到:registerBeanDefinitions()。QBM28資訊網(wǎng)——每日最新資訊28at.com

注冊(cè) BeanDefinitions。QBM28資訊網(wǎng)——每日最新資訊28at.com

public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {		BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();		// 得到容器中注冊(cè)的bean數(shù)量		int countBefore = getRegistry().getBeanDefinitionCount();		// 解析過程入口,這里使用了委派模式		documentReader.registerBeanDefinitions(doc, createReaderContext(resource));		// 統(tǒng)計(jì)解析的bean數(shù)量		return getRegistry().getBeanDefinitionCount() - countBefore;	}

再深入registerBeanDefinitions()方法(該方法是委派模式的結(jié)果):QBM28資訊網(wǎng)——每日最新資訊28at.com

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

再深入doRegisterBeanDefinitions(doc.getDocumentElement());:QBM28資訊網(wǎng)——每日最新資訊28at.com

真正開始注冊(cè) BeanDefinitions :QBM28資訊網(wǎng)——每日最新資訊28at.com

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解析定義之前,進(jìn)行自定義解析,看是否是用戶自定義標(biāo)簽		preProcessXml(root);		// 開始進(jìn)行解析bean定義的document對(duì)象		parseBeanDefinitions(root, this.delegate);		// 解析bean定義之后,進(jìn)行自定義的解析,增加解析過程的可擴(kuò)展性		postProcessXml(root);		this.delegate = parent;	}

接下來看parseBeanDefinitions(root, this.delegate)。QBM28資訊網(wǎng)——每日最新資訊28at.com

document的根元素開始進(jìn)行解析翻譯成BeanDefinitions。QBM28資訊網(wǎng)——每日最新資訊28at.com

// 從document的根元素開始進(jìn)行解析翻譯成BeanDefinitions	protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {		// bean定義的document對(duì)象使用了spring默認(rèn)的xml命名空間		if (delegate.isDefaultNamespace(root)) {			// 獲取bean定義的document對(duì)象根元素的所有字節(jié)點(diǎn)			NodeList nl = root.getChildNodes();			for (int i = 0; i < nl.getLength(); i++) {				Node node = nl.item(i);				// 獲得document節(jié)點(diǎn)是xml元素節(jié)點(diǎn)				if (node instanceof Element) {					Element ele = (Element) node;					// bean定義的document的元素節(jié)點(diǎn)使用的是spring默認(rèn)的xml命名空間					if (delegate.isDefaultNamespace(ele)) {						// 使用spring的bean規(guī)則解析元素 節(jié)點(diǎn)						parseDefaultElement(ele, delegate);					}					else {						// 沒有使用spring默認(rèn)的xml命名空間,則使用用戶自定義的解析規(guī)則解析元素節(jié)點(diǎn)						delegate.parseCustomElement(ele);					}				}			}		}		else {			delegate.parseCustomElement(root);		}	}	private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {		// 解析 <import> 標(biāo)簽元素,并進(jìn)行導(dǎo)入解析		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);這三個(gè)方法里分別展示了標(biāo)簽解析的詳細(xì)過程。
這下看到了,它其實(shí)使用DOM4J來解析import bean alias等標(biāo)簽,然后遞歸標(biāo)簽內(nèi)部直到拿到所有屬性并封裝到BeanDefition對(duì)象中。比如說processBeanDefinition方法。QBM28資訊網(wǎng)——每日最新資訊28at.com

給我一個(gè)element 解析成 BeanDefinition。QBM28資訊網(wǎng)——每日最新資訊28at.com

// 給我一個(gè)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.				// 注冊(cè): 將db注冊(cè)到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));		}	}

繼續(xù)深入registerBeanDefinition()。QBM28資訊網(wǎng)——每日最新資訊28at.com

注冊(cè)BeanDefinitions 到 bean 工廠。QBM28資訊網(wǎng)——每日最新資訊28at.com

// 注冊(cè)BeanDefinitions 到 bean 工廠	// definitionHolder : bean定義,包含了 name和aliases	// registry: 注冊(cè)到的bean工廠	public static void registerBeanDefinition(			BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)			throws BeanDefinitionStoreException {		// Register bean definition under primary name.		String beanName = definitionHolder.getBeanName();		// 真正注冊(cè)		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())。QBM28資訊網(wǎng)——每日最新資訊28at.com

注冊(cè)BeanDefinitions 到IOC容器。QBM28資訊網(wǎng)——每日最新資訊28at.com

注意:該方法所在類是接口,我們查看的是DefaultListableBeanFactory.java所實(shí)現(xiàn)的該方法。QBM28資訊網(wǎng)——每日最新資訊28at.com

// 實(shí)現(xiàn)BeanDefinitionRegistry接口,注冊(cè)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");		// 校驗(yàn)是否是 AbstractBeanDefinition)		if (beanDefinition instanceof AbstractBeanDefinition) {			try {				// 標(biāo)記 beanDefinition 生效				((AbstractBeanDefinition) beanDefinition).validate();			}			catch (BeanDefinitionValidationException ex) {				throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,						"Validation of bean definition failed", ex);			}		}		// 判斷beanDefinitionMap 里是否已經(jīng)有這個(gè)bean		BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);		//如果沒有這個(gè)bean		if (existingDefinition != null) {			//如果不允許bd 覆蓋已注冊(cè)的bean, 就拋出異常			if (!isAllowBeanDefinitionOverriding()) {				throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);			}			// 如果允許覆蓋, 則同名的bean, 注冊(cè)的覆蓋先注冊(cè)的			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 + "]");				}			}			// 注冊(cè)到容器,beanDefinitionMap 就是個(gè)容器			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);		}	}

這個(gè)方法中對(duì)所需要加載的bean進(jìn)行校驗(yàn),沒有問題的話就put到beanDefinitionMap中,beanDefinitionMap其實(shí)就是IOC.這樣我們的Bean就被加載到IOC容器中了。QBM28資訊網(wǎng)——每日最新資訊28at.com

本文鏈接:http://m.www897cc.com/showinfo-26-11758-0.html徹底搞懂Spring的Bean加載

聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。郵件:2376512515@qq.com

上一篇: 一個(gè)關(guān)于 i++ 和 ++i 的面試題打趴了所有人

下一篇: 玩轉(zhuǎn)SpringBoot—自動(dòng)裝配解決Bean的復(fù)雜配置

標(biāo)簽:
  • 熱門焦點(diǎn)
Top 日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不
亚洲欧美一区二区三区极速播放 | 国产麻豆91精品| 欧美日韩无遮挡| 国产精品久久久久国产精品日日| 国产精品亚洲综合天堂夜夜| 国产专区综合网| 亚洲黄色小视频| 亚洲一区二区在线看| 久久成人在线| 欧美韩国一区| 国产精品久久久久一区二区三区共 | 一区二区成人精品| 欧美亚洲尤物久久| 欧美va亚洲va国产综合| 欧美性淫爽ww久久久久无| 国产在线乱码一区二区三区| 91久久夜色精品国产九色| 亚洲主播在线| 欧美aa国产视频| 国产精品免费观看视频| 亚洲电影免费在线| 亚洲一区二区三区国产| 久久蜜桃av一区精品变态类天堂| 欧美日本在线视频| 国产一区亚洲| 一区二区三区四区五区精品| 久久精品一二三区| 欧美午夜精品理论片a级大开眼界 欧美午夜精品理论片a级按摩 | 激情成人综合| 在线亚洲免费| 女主播福利一区| 国产精品亚洲综合天堂夜夜| 亚洲精品一区二区网址| 性欧美精品高清| 欧美日韩你懂的| 亚洲第一中文字幕| 欧美一区二区高清在线观看| 欧美日韩午夜在线| 在线免费观看视频一区| 西西裸体人体做爰大胆久久久| 欧美韩国在线| 禁久久精品乱码| 国产精品每日更新| 亚洲精品久久久一区二区三区| 久久不射中文字幕| 国产精品国产三级欧美二区| 亚洲精品1区| 久久精品一本| 国产精品丝袜久久久久久app | 久久久亚洲国产美女国产盗摄| 国产精品高潮久久| 亚洲日韩欧美一区二区在线| 久久久久久久综合| 国产欧美日韩在线| 亚洲自拍都市欧美小说| 欧美日本高清一区| 91久久中文| 久久综合精品国产一区二区三区| 国产欧美日韩免费看aⅴ视频| 在线视频你懂得一区| 欧美www在线| 永久久久久久| 久久久久久亚洲综合影院红桃 | 国产日韩在线亚洲字幕中文| 亚洲一区二区三区激情| 欧美三级黄美女| 日韩视频中文字幕| 欧美韩日亚洲| 亚洲欧洲精品天堂一级| 猛男gaygay欧美视频| 伊人婷婷久久| 久久亚洲精品一区二区| 伊人成人在线视频| 久久久久免费视频| 狠狠色丁香婷婷综合久久片| 性做久久久久久免费观看欧美 | 狠狠色综合网站久久久久久久| 欧美在线播放高清精品| 国产伦精品一区二区三区高清| 亚洲综合国产激情另类一区| 国产精品久久久久久模特| 亚洲欧美日韩电影| 国产精品一区二区三区乱码| 亚洲欧美视频| 国产欧美一区二区三区视频| 欧美在线播放一区| 国产一区二区你懂的| 久久九九热re6这里有精品| 狠狠v欧美v日韩v亚洲ⅴ| 久久蜜桃av一区精品变态类天堂| 一区二区在线观看视频在线观看| 久久婷婷蜜乳一本欲蜜臀| 影音先锋中文字幕一区| 老牛嫩草一区二区三区日本| 亚洲国产你懂的| 欧美噜噜久久久xxx| aa成人免费视频| 国产精品地址| 性色av香蕉一区二区| 国产亚洲精品久久久久久| 久久久av水蜜桃| 亚洲电影一级黄| 欧美日本国产一区| 亚洲一区在线直播| 国产三区精品| 久久人人爽人人| 亚洲人成在线影院| 欧美色图首页| 性色av一区二区怡红| 在线免费观看日本一区| 欧美极品一区| 亚洲综合精品四区| 黄色成人在线网站| 欧美人在线视频| 亚洲欧美资源在线| 一区久久精品| 欧美日韩18| 久久超碰97中文字幕| 亚洲韩国青草视频| 国产精品爱久久久久久久| 久久福利毛片| 亚洲免费av片| 国产欧美日韩不卡| 久久综合九九| 国产精品99久久99久久久二8 | 亚洲精品日韩精品| 国产精品视频免费观看| 久久久久久久一区二区三区| 亚洲精选中文字幕| 国产欧美日韩亚洲精品| 免费欧美日韩国产三级电影| 一区二区动漫| 国内精品美女在线观看| 欧美精品情趣视频| 欧美一区二区日韩一区二区| 亚洲欧洲日韩女同| 国产精品中文在线| 亚洲欧洲一区二区在线播放| 欧美日韩在线一区二区| 久久久精品欧美丰满| 亚洲乱码国产乱码精品精| 国产日韩欧美精品| 欧美久久久久久久| 欧美一区二区视频免费观看| 亚洲精品国产无天堂网2021| 国产伦精品一区二区三区在线观看| 久久亚洲国产成人| 亚洲一区二区欧美| 在线日韩电影| 国产欧美精品在线观看| 欧美精品免费看| 久久久久国产一区二区三区| 亚洲天堂av在线免费观看| 在线免费不卡视频| 国产偷国产偷亚洲高清97cao| 欧美日本簧片| 蜜臀av在线播放一区二区三区| 亚洲欧美日韩一区二区三区在线| 亚洲欧洲日产国码二区| 国产视频在线观看一区二区三区 | 久久亚洲综合色| 亚洲欧美一区二区视频| 亚洲美女电影在线| 有坂深雪在线一区| 国产欧美日韩麻豆91| 欧美日韩国产一级| 狂野欧美激情性xxxx欧美| 亚洲欧美亚洲| 这里只有精品电影| 亚洲欧洲一区二区天堂久久| 在线观看91精品国产麻豆| 国产日本欧美视频| 国产精品久久一卡二卡| 欧美日韩伦理在线| 欧美成人免费网站| 久久男女视频| 久久国产视频网| 亚洲欧美视频一区| 亚洲一区二区在线看| 夜色激情一区二区| 亚洲精品日韩激情在线电影| 亚洲国产成人精品久久久国产成人一区 | 国产酒店精品激情| 欧美性一区二区| 欧美日韩系列| 欧美精品精品一区| 欧美成人69| 蜜桃久久精品乱码一区二区| 久久青草久久| 久久亚洲欧美国产精品乐播| 欧美在线观看视频| 小黄鸭精品aⅴ导航网站入口| 亚洲一区bb| 亚洲午夜免费福利视频| 一区二区三区国产盗摄| 99国内精品久久久久久久软件| 91久久国产精品91久久性色| 亚洲高清资源综合久久精品| 亚洲第一免费播放区| 亚洲福利视频在线| 亚洲国产1区| 亚洲精品美女免费| 亚洲免费不卡| 在线亚洲伦理|