Spring原始碼學習筆記之基於ClassPathXmlApplicationContext進行bean標籤解析
阿新 • • 發佈:2019-12-14
bean 標籤在spring的配置檔案中, 是非常重要的一個標籤, 即便現在boot專案比較流行, 但是還是有必要理解bean標籤的解析流程,有助於我們進行
基於註解配置, 也知道各個標籤的作用,以及是怎樣被spring識別的, 以及配置的時候需要注意的點.
傳統的spring專案,spring內部啟動的方式是基於ClassPathXmlApplicationContext啟動的:
@Test public void test1() {
//傳入spring的配置檔案路徑 ApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("spring.xml"); System.out.println(""); }
// 呼叫有參構造,設定spring配置檔案的位置
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
//進一步跟進
public ClassPathXmlApplicationContext(
String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
throws BeansException {
// 此處parent 為null
super(parent);
//建立解析器,解析configLocations
setConfigLocations(configLocations);
// refresh = true
if (refresh) {
//重新整理spring容器,bean標籤的核心方法
refresh();
}
}
//進一步跟進refresh 方法
public Collection<ApplicationListener<?>> getApplicationListeners() {
return this.applicationListeners;
}
/*
* 該方法是spring容器初始化的核心方法。是spring容器初始化的核心流程,是一個典型的父類模板設計模式的運用
* 根據不同的上下文物件,會掉到不同的上下文物件子類方法中
*
* 核心上下文子類有:
* ClassPathXmlApplicationContext
* FileSystemXmlApplicationContext
* AnnotationConfigApplicationContext
* EmbeddedWebApplicationContext(springboot)
*
* 方法重要程度:
* 0:不重要,可以不看
* 1:一般重要,可看可不看
* 5:非常重要,一定要看
* */
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//為容器初始化做準備,重要程度:0
// Prepare this context for refreshing.
prepareRefresh();
/*
重要程度:5
1、建立BeanFactory物件
* 2、xml解析
* 傳統標籤解析:bean、import等
* 自定義標籤解析 如:<context:component-scan base-package="com.xiangxue.jack"/>
* 自定義標籤解析流程:
* a、根據當前解析標籤的頭資訊找到對應的namespaceUri
* b、載入spring所以jar中的spring.handlers檔案。並建立對映關係
* c、根據namespaceUri從對映關係中找到對應的實現了NamespaceHandler介面的類
* d、呼叫類的init方法,init方法是註冊了各種自定義標籤的解析類
* e、根據namespaceUri找到對應的解析類,然後呼叫paser方法完成標籤解析
*
* 3、把解析出來的xml標籤封裝成BeanDefinition物件
* */
// Tell the subclass to refresh the internal bean factory.
//此處建立bean 工廠, 解析bean 標籤以及處理 component-scan 標籤的核心方法
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
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();
}
}
}
//進一步跟進建立bean工廠的方法obtainFreshBeanFactory,研究bean 標籤的解析邏輯
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
//核心方法,必須讀,重要程度:5
refreshBeanFactory();
return getBeanFactory();
}
//再一步跟進refreshBeanFactory 方法
跟到這裡,我們發現分叉了, 有 多個實現類, 那麼是跟哪一個呢?
這個是使我們看一下類的繼承關係圖
很明顯這個時候我們再次跟進的時候需要看的跟的就是org.springframework.context.support.AbstractRefreshableApplicationContext#refreshBeanFactory ,我們再次跟蹤
@Override protected final void refreshBeanFactory() throws BeansException { //如果BeanFactory不為空,則清除BeanFactory和裡面的例項
// 由於我們的容器剛啟動,所以這裡自然也是false if (hasBeanFactory()) { destroyBeans(); closeBeanFactory(); } try { //建立DefaultListableBeanFactory DefaultListableBeanFactory beanFactory = createBeanFactory();
beanFactory.setSerializationId(getId()); //設定是否可以迴圈依賴 allowCircularReferences //是否允許使用相同名稱重新註冊不同的bean實現. customizeBeanFactory(beanFactory); //解析xml,並把xml中的標籤封裝成BeanDefinition物件 loadBeanDefinitions(beanFactory); synchronized (this.beanFactoryMonitor) { this.beanFactory = beanFactory; } } catch (IOException ex) { throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex); } }
// 進一步跟進spring容器載入beandefinition物件的過程
@Override
protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
// Create a new XmlBeanDefinitionReader for the given BeanFactory.
//建立xml的解析器,這裡是一個委託模式
XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
// Configure the bean definition reader with this context's
// resource loading environment.
beanDefinitionReader.setEnvironment(this.getEnvironment());
//這裡傳一個this進去,因為ApplicationContext是實現了ResourceLoader介面的
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);
//主要看這個方法 重要程度 5
loadBeanDefinitions(beanDefinitionReader);
}
設定資源載入器設定了this 物件象,這是因為當前物件是.AbstractRefreshableApplicationContext,繼承自DefaultResourceLoader,
而DefaultResourceLoader 實現了Resourloader 介面
接著上面的原始碼,進一步跟進核心方法loadBeanDefinitions :
//這裡需要我們回憶一下我們最初的構造器,引數是設定到 configLocation 裡面去了,所以這裡設定核心關注點在從configLocations 中解析xml檔案,解析bean標籤
protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException { Resource[] configResources = getConfigResources(); if (configResources != null) { reader.loadBeanDefinitions(configResources); } //獲取需要載入的xml配置檔案 String[] configLocations = getConfigLocations(); if (configLocations != null) { reader.loadBeanDefinitions(configLocations); } }
//進一步跟進loadBeanDefinitions(String args) 這個方法
@Override
public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
Assert.notNull(locations, "Location array must not be null");
int count = 0;
//配置檔案有多個,載入多個配置檔案
for (String location : locations) {
//這裡的數量是beandefination的數量
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 = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
//把字串型別的xml檔案路徑,形如:classpath*:user/**/*-context.xml,轉換成Resource物件型別,其實就是用流
//的方式載入配置檔案,然後封裝成Resource物件,不重要,可以不看
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//主要看這個方法 ** 重要程度 5
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 {
// 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;
}
}
// 再進一步跟蹤loadBeanDefinitions 方法
public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
}
if (resourceLoader instanceof ResourcePatternResolver) {
// Resource pattern matching available.
try {
//把字串型別的xml檔案路徑,形如:classpath*:user/**/*-context.xml,轉換成Resource物件型別,其實就是用流
//的方式載入配置檔案,然後封裝成Resource物件,不重要,可以不看
Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
//主要看這個方法 ** 重要程度 5
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 {
// 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;
}
}
// 進一步跟蹤loadBeanDefinitions(resources) 方法
由於程式碼很深, 跟著跟著很有可能就跟丟了,這個時候debug 一下:
那麼我們繼續
// 進一步跟蹤loadBeanDefinitions(resources) 方法
@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 resource) throws BeanDefinitionStoreException {
//EncodedResource帶編碼的對Resource物件的封裝
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 == 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 {
//獲取Resource物件中的xml檔案流物件
InputStream inputStream = encodedResource.getResource().getInputStream();
try {
//InputSource是jdk中的sax xml檔案解析物件
InputSource inputSource = new InputSource(inputStream);
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//主要看這個方法 ** 重要程度 5
// 這裡才是真正開始解析,封裝beanDifination物件
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();
}
}
}
//進一步跟蹤如下
// 載入xml,解析document,將其中的元素封裝為beandefinition 並註冊
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//把inputSource 封裝成Document檔案物件,這是jdk的API
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);
}
}
//進一步跟蹤原始碼
// 建立reader 讀取document,並將其封裝為 beandefination,以及並註冊
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
//又來一記委託模式,BeanDefinitionDocumentReader委託這個類進行document的解析
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
int countBefore = getRegistry().getBeanDefinitionCount();
//主要看這個方法,createReaderContext(resource) XmlReaderContext上下文,封裝了XmlBeanDefinitionReader物件
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
return getRegistry().getBeanDefinitionCount() - countBefore;
}
其中部分呼叫方法簡單做一下分析
//public XmlReaderContext createReaderContext(Resource resource) {
// return new XmlReaderContext(resource, this.problemReporter, this.eventListener,
//獲取名稱空間解析器,後續用來判斷是否預設的名稱空間, 針對不同的名稱空間進行處理
// this.sourceExtractor, this, getNamespaceHandlerResolver());
//}
// 回到主流程進行進一步分析,以及跟蹤
@Override
public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
this.readerContext = readerContext;
//主要看這個方法,把root節點傳進去
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.
//建立BeanDefinitionParser 的委託類,並進行預設屬性的的設定
// 如果bean的屬性沒有設定,則使用預設值得預設屬性
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
//判斷是否預設的名稱空間的依據是否是beans開始的,開始的則是預設的名稱空間 否則就不是
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);
//主要看這個方法,標籤具體解析過程
parseBeanDefinitions(root, this.delegate);
// 後置處理 模板設計模式 , springmvc 中的interceptor
postProcessXml(root);
this.delegate = parent;
}
在這裡我們需要留意一下建立解析方法,其中有做預設屬性的處理
//開始解析元素, 根據名稱空間是否預設名稱空間,解析方式不一樣 // 其中涉及到bean 解析的其實是兩種都有設計到, bean 標籤沒帶字首,為預設命名空 // 開啟註解的<context:component-scan= "basepacakge "> 非預設的名稱空間 // 我們的bean 標籤不屬於自定義標籤 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)) { //預設標籤解析 parseDefaultElement(ele, delegate); } else { //自定義標籤解析 delegate.parseCustomElement(ele); } } } } else { delegate.parseCustomElement(root); } } //這裡我們先跟蹤bean 基於xml的bean 標籤解析 // bean 標籤屬於預設標籤 private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) { //import標籤解析 重要程度 1 ,可看可不看 if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) { importBeanDefinitionResource(ele); } //alias標籤解析 別名標籤 重要程度 1 ,可看可不看 else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) { processAliasRegistration(ele); } //bean標籤,重要程度 5,必須看 // 如果是bean 標籤,則進步解析為beanDefinition 物件 else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) { processBeanDefinition(ele, delegate); } else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) { // recurse doRegisterBeanDefinitions(ele); } }
//解析bean 標籤並封裝成beandefinitionHolder 物件
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//重點看這個方法,重要程度 5 ,解析document,封裝成BeanDefinition
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
//該方法功能不重要,設計模式重點看一下,裝飾者設計模式,加上SPI設計思想
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
//完成document到BeanDefinition物件轉換後,對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));
}
}
//進一步跟蹤
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele) {
return parseBeanDefinitionElement(ele, null);
}
//進一步跟蹤
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
String beanName = id;
// 當bean 為空, 並且 別名不為空的情況下, 取第一個別名作為bean的別名
if (!StringUtils.hasText(beanName) && !aliases.isEmpty()) {
beanName = aliases.remove(0);
if (logger.isTraceEnabled()) {
logger.trace("No XML 'id' specified - using '" + beanName +
"' as bean name and " + aliases + " as aliases");
}
}
//檢查beanName是否重複
if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
// 核心方法.解析元素封裝為beandefinition物件
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
// 如果即沒有name 屬性也沒有id 屬性,此時bean沒有名稱
// 這裡生成beanName
// xml 方式的beanName 為 全限定命名#數字 如果 com.test.Student#0
beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {
aliases.add(beanClassName);
}
}
if (logger.isTraceEnabled()) {
logger.trace("Neither XML 'id' nor 'name' specified - " +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {
error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
//進一步跟蹤封裝成為beanDefinition物件的全過程
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
this.parseState.push(new BeanEntry(beanName));
String className = null;
// 獲取class 屬性
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
// 獲取parent 屬性
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
//建立GenericBeanDefinition物件
// 這裡的beandefinition 物件是GenericBeanDefinition
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
//解析bean標籤的屬性,並把解析出來的屬性設定到BeanDefinition物件中
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
//解析bean中的meta標籤
parseMetaElements(ele, bd);
//解析bean中的lookup-method標籤 重要程度:2,可看可不看
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//解析bean中的replaced-method標籤 重要程度:2,可看可不看
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析bean中的constructor-arg標籤 重要程度:2,可看可不看
parseConstructorArgElements(ele, bd);
//解析bean中的property標籤 重要程度:2,可看可不看
parsePropertyElements(ele, bd);
//可以不看,用不到
parseQualifierElements(ele, bd);
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
}
catch (ClassNotFoundException ex) {
error("Bean class [" + className + "] not found", ele, ex);
}
catch (NoClassDefFoundError err) {
error("Class that bean class [" + className + "] depends on not found", ele, err);
}
catch (Throwable ex) {
error("Unexpected failure during bean definition parsing", ele, ex);
}
finally {
this.parseState.pop();
}
return null;
}
// 屬性解析的邏輯
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
@Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {
if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {
error("Old 1.x 'singleton' attribute in use - upgrade to 'scope' declaration", ele);
}
// 解析scope 屬性
else if (ele.hasAttribute(SCOPE_ATTRIBUTE)) {
bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE));
}
else if (containingBean != null) {
// Take default from containing bean in case of an inner bean definition.
bd.setScope(containingBean.getScope());
}
// 解析abstract 屬性
if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) {
bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE)));
}
// 從解析委託類中獲取預設屬性值lazy_init
String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
if (DEFAULT_VALUE.equals(lazyInit)) {
lazyInit = this.defaults.getLazyInit();
}
bd.setLazyInit(TRUE_VALUE.equals(lazyInit));
String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
bd.setAutowireMode(getAutowireMode(autowire));
// depends-on 屬性
if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {
String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE);
bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, MULTI_VALUE_ATTRIBUTE_DELIMITERS));
}
String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE);
if ("".equals(autowireCandidate) || DEFAULT_VALUE.equals(autowireCandidate)) {
String candidatePattern = this.defaults.getAutowireCandidates();
if (candidatePattern != null) {
String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
}
}
else {
bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate));
}
//這個primary 屬性
if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) {
bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE)));
}
// init-method 屬性
if (ele.hasAttribute(INIT_METHOD_ATTRIBUTE)) {
String initMethodName = ele.getAttribute(INIT_METHOD_ATTRIBUTE);
bd.setInitMethodName(initMethodName);
}
else if (this.defaults.getInitMethod() != null) {
bd.setInitMethodName(this.defaults.getInitMethod());
bd.setEnforceInitMethod(false);
}
//destory-method
if (ele.hasAttribute(DESTROY_METHOD_ATTRIBUTE)) {
String destroyMethodName = ele.getAttribute(DESTROY_METHOD_ATTRIBUTE);
bd.setDestroyMethodName(destroyMethodName);
}
else if (this.defaults.getDestroyMethod() != null) {
bd.setDestroyMethodName(this.defaults.getDestroyMethod());
bd.setEnforceDestroyMethod(false);
}
//factory-method
if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE));
}
//factory-bean 屬性
if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) {
bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE));
}
return bd;
}
//到此,spring 解析bean 標籤基本完後,我們在回過去看bean標籤解析完成後,做了什麼處理
//beandefinition 解析完成後,註冊到bean 註冊中心中去,後續例項化的時候再去取用
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
//完成BeanDefinition的註冊,重點看,重要程度 5
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
//建立別名和 id的對映,這樣就可以根據別名獲取到id
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
// 註冊beandefinitionholder 到bean 註冊中心中
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
//完成BeanDefinition的註冊,重點看,重要程度 5
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
//建立別名和 id的對映,這樣就可以根據別名獲取到id
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {
for (String alias : aliases) {
registry.registerAlias(beanName, alias);
}
}
}
至此,bean 標籤的解析流程基本結束, 如果用流程圖表示整個過程的話,整個過程的整體流程如圖所示:
後續會繼續完善開啟註解掃描部分的講解.即<context:component-scan="basepackage"> 標籤的解析流程.