/*
這裏分別使用
裝飾者模式:使用EncodedResource包裝Resource,對編碼進行處理
策略模式:Resource針對不同的資源實現了,實現了不同的策略
*/
@Override
public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
return loadBeanDefinitions(new EncodedResource(resource));
}
/*
緩存encodedResource
獲取sax包下InputSource,並設置編碼
加載BeanDefinitions
清除緩存值
*/
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 inputStream = encodedResource.getResource().getInputStream();
try {
//sax包下InputSource
InputSource inputSource = new InputSource(inputStream);
//設置編碼,一般爲空
if (encodedResource.getEncoding() != null) {
inputSource.setEncoding(encodedResource.getEncoding());
}
//加載BeanDefinitions
//inputSource:sax解析器流,encodedResource.getResource()spring傳入的資源對象
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
解析document註冊bean定義
*/
protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
throws BeanDefinitionStoreException {
try {
//加載xml,獲取對應document
Document doc = doLoadDocument(inputSource, resource);
//根據document註冊bean信息
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);
}
}
/*
採用DefaultDocumentLoader加載XML流
*/
protected Document doLoadDocument(InputSource inputSource, Resource resource) throws Exception {
return this.documentLoader.loadDocument(inputSource,
//提供如何尋找DTD聲明的方法,有可能根據網絡,也可能根據本地路徑
getEntityResolver(),
//主要對錯誤的記錄以及打印
this.errorHandler,
//獲取對xml的驗證模式,判斷是否包含DOCTYPE,如果包含則DTD,否則XSD驗證
getValidationModeForResource(resource),
//此解析器是否被配置爲可識別名稱空間
isNamespaceAware());
}
/*
根據判斷ResourceLoader來設置解析器
*/
protected EntityResolver getEntityResolver() {
if (this.entityResolver == null) {
// Determine default EntityResolver to use.
ResourceLoader resourceLoader = getResourceLoader();
//XmlBeanFactory創建this的時候傳入了這個值
//private final XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(this);
if (resourceLoader != null) {
//BeansDtdResolver:使用默認的DTD解析
//PluggableSchemaResolver:設置META-INF/spring.schemas路徑,該文件有xsd路徑地址
this.entityResolver = new ResourceEntityResolver(resourceLoader);
}
else {
//通過resolveEntity方法解析
this.entityResolver = new DelegatingEntityResolver(getBeanClassLoader());
}
}
return this.entityResolver;
}
/*
是否使用自動驗證模式
否,手動
自動檢測驗證模式
否:使用自動檢測後的模式
是:默認XSD
*/
protected int getValidationModeForResource(Resource resource) {
int validationModeToUse = getValidationMode();
//使用手動指定的驗證模式
if (validationModeToUse != VALIDATION_AUTO) {
return validationModeToUse;
}
//使用自動檢測,默認使用
int detectedMode = detectValidationMode(resource);
if (detectedMode != VALIDATION_AUTO) {
return detectedMode;
}
// Hmm, we didn't get a clear indication... Let's assume XSD,
// since apparently no DTD declaration has been found up until
// detection stopped (before finding the document's root tag).
return VALIDATION_XSD;
}
/*
遍歷每一行
查看是否DOCTYPE,如果有,則VALIDATION_DTD
讀取到<開始符號,驗證模式一定會在開始符號之前VALIDATION_XSD
異常,則默認自動檢測
*/
public int detectValidationMode(InputStream inputStream) throws IOException {
// Peek into the file to look for DOCTYPE.
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
boolean isDtdValidated = false;
String content;
while ((content = reader.readLine()) != null) {
content = consumeCommentTokens(content);
//讀取行爲空或者註釋,省略
if (this.inComment || !StringUtils.hasText(content)) {
continue;
}
//查看是否DOCTYPE,如果有,則VALIDATION_DTD
if (hasDoctype(content)) {
isDtdValidated = true;
break;
}
//讀取到<開始符號,驗證模式一定會在開始符號之前VALIDATION_XSD
if (hasOpeningTag(content)) {
// End of meaningful data...
break;
}
}
return (isDtdValidated ? VALIDATION_DTD : VALIDATION_XSD);
}
catch (CharConversionException ex) {
// Choked on some character encoding...
// Leave the decision up to the caller.
return VALIDATION_AUTO;
}
finally {
reader.close();
}
}
/*
創建工廠,且內部設置是否開啓驗證以及是否XSD解析等值
根據工廠創建解析器,內部封裝日誌以及自定義dtd以及xsd解析器
解析
*/
@Override
public Document loadDocument(InputSource inputSource, EntityResolver entityResolver,
ErrorHandler errorHandler, int validationMode, boolean namespaceAware) throws Exception {
// 創建工廠,jaxp內庫,內部調用sax以及dom解析
DocumentBuilderFactory factory = createDocumentBuilderFactory(validationMode, namespaceAware);
if (logger.isTraceEnabled()) {
logger.trace("Using JAXP provider [" + factory.getClass().getName() + "]");
}
/*
javax自帶解析器
factory:com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl
entityResolver:封裝了dtd解析器以及xsd默認解析路徑
errorHandler:log
得到dom解析器
*/
DocumentBuilder builder = createDocumentBuilder(factory, entityResolver, errorHandler);
// 解析xml文件,得到代表文檔的document
return builder.parse(inputSource);
}
/*
解析後會調用內部設置的解析器解析
父類解析
當父類沒解析,調用子類解析
解碼xsd的url且獲取路徑
獲取本地項目根路徑
當xsd和本地項目路徑一直,說明xsd是本地路徑,保存本地路徑地址
本地路徑地址不爲空,則解析
生成InputSource,內部流是本地文件流
爲空,則從網絡下載文件,然後設置流
*/
public InputSource resolveEntity(@Nullable String publicId, @Nullable String systemId)
throws SAXException, IOException {
//父類解析
InputSource source = super.resolveEntity(publicId, systemId);
//說明父類沒解析,在來xsd解析
if (source == null && systemId != null) {
String resourcePath = null;
try {
//解碼xsd的url
String decodedSystemId = URLDecoder.decode(systemId, "UTF-8");
String givenUrl = new URL(decodedSystemId).toString();
//獲取本地項目根路徑
//toURI此方法不會自動將鏈接中的非法字符轉義。而在File轉化成URI的時候,會將鏈接中的特殊字符如#或!等字符進行編碼。
String systemRootUrl = new File("").toURI().toURL().toString();
// Try relative to resource base if currently in system root.
//2者相同說明文件在本地,這裏截取目錄地址,獲取root相對路徑
if (givenUrl.startsWith(systemRootUrl)) {
resourcePath = givenUrl.substring(systemRootUrl.length());
}
}
catch (Exception ex) {
// Typically a MalformedURLException or AccessControlException.
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve XML entity [" + systemId + "] against system root URL", ex);
}
// No URL (or no resolvable URL) -> try relative to resource base.
resourcePath = systemId;
}
//資源路徑不爲空xsd說明在本地
if (resourcePath != null) {
if (logger.isTraceEnabled()) {
logger.trace("Trying to locate XML entity [" + systemId + "] as resource [" + resourcePath + "]");
}
Resource resource = this.resourceLoader.getResource(resourcePath);
//替換成本地文件流
source = new InputSource(resource.getInputStream());
source.setPublicId(publicId);
source.setSystemId(systemId);
if (logger.isDebugEnabled()) {
logger.debug("Found XML entity [" + systemId + "]: " + resource);
}
}
else if (systemId.endsWith(DTD_SUFFIX) || systemId.endsWith(XSD_SUFFIX)) {
// External dtd/xsd lookup via https even for canonical http declaration
String url = systemId;
//轉成https
if (url.startsWith("http:")) {
url = "https:" + url.substring(5);
}
try {
//url網絡下載解析
source = new InputSource(new URL(url).openStream());
source.setPublicId(publicId);
source.setSystemId(systemId);
}
catch (IOException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not resolve XML entity [" + systemId + "] through URL [" + url + "]", ex);
}
// Fall back to the parser's default behavior.
source = null;
}
}
}
return source;
}
/*
publicId:已經可以表示任何位置的外部DTD資源了,但是它是直接指向相應的資源,publicId的作用在於其間接性。
systemId:外部資源(多半是DTD)的URI,比如本地文件file:///usr/share/dtd/somefile.dtd或者網絡某個地址的文件http://www.w3.org/somefile.dtd;
publicId=-//SPRING//DTD BEAN//EN
systemId=http://www.springframework.org/dtd:/spring-beans.dtd
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd:/spring-beans.dtd">
publicId=null
systemId=http://www.springframework.org/schema/context/spring-context-4.0.xsd
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
分別解析dtd以及xsd
*/
@Override
@Nullable
public InputSource resolveEntity(@Nullable String publicId, @Nullable String systemId)
throws SAXException, IOException {
if (systemId != null) {
if (systemId.endsWith(DTD_SUFFIX)) {
//如果是dtd這裏解析
return this.dtdResolver.resolveEntity(publicId, systemId);
}
else if (systemId.endsWith(XSD_SUFFIX)) {
///META-INF/spring.schemes解析
return this.schemaResolver.resolveEntity(publicId, systemId);
}
}
// Fall back to the parser's default behavior.
return null;
}
/*
緩存中獲取資源
如果是https解析成http獲取緩存
獲取本地資源
*/
@Override
@Nullable
public InputSource resolveEntity(@Nullable String publicId, @Nullable String systemId) throws IOException {
if (logger.isTraceEnabled()) {
logger.trace("Trying to resolve XML entity with public id [" + publicId +
"] and system id [" + systemId + "]");
}
if (systemId != null) {
String resourceLocation = getSchemaMappings().get(systemId);
//解析成http獲取緩存
if (resourceLocation == null && systemId.startsWith("https:")) {
// Retrieve canonical http schema mapping even for https declaration
resourceLocation = getSchemaMappings().get("http:" + systemId.substring(6));
}
if (resourceLocation != null) {
//封裝本地資源
Resource resource = new ClassPathResource(resourceLocation, this.classLoader);
try {
InputSource source = new InputSource(resource.getInputStream());
source.setPublicId(publicId);
source.setSystemId(systemId);
if (logger.isTraceEnabled()) {
logger.trace("Found XML schema [" + systemId + "] in classpath: " + resourceLocation);
}
return source;
} catch (FileNotFoundException ex) {
if (logger.isDebugEnabled()) {
logger.debug("Could not find XML schema [" + systemId + "]: " + resource, ex);
}
}
}
}
// Fall back to the parser's default behavior.
return null;
}
/*
從spring.schemas獲取資源
*/
private Map<String, String> getSchemaMappings() {
Map<String, String> schemaMappings = this.schemaMappings;
if (schemaMappings == null) {
synchronized (this) {
schemaMappings = this.schemaMappings;
if (schemaMappings == null) {
if (logger.isTraceEnabled()) {
logger.trace("Loading schema mappings from [" + this.schemaMappingsLocation + "]");
}
try {
Properties mappings =
PropertiesLoaderUtils.loadAllProperties(this.schemaMappingsLocation, this.classLoader);
if (logger.isTraceEnabled()) {
logger.trace("Loaded schema mappings: " + mappings);
}
schemaMappings = new ConcurrentHashMap<>(mappings.size());
CollectionUtils.mergePropertiesIntoMap(mappings, schemaMappings);
this.schemaMappings = schemaMappings;
} catch (IOException ex) {
throw new IllegalStateException(
"Unable to load schema mappings from location [" + this.schemaMappingsLocation + "]", ex);
}
}
}
}
return schemaMappings;
}
/*
當設置路徑的時候,schemaMappings默認初始化了
這個問題是因爲編輯器爲了debug方便(因爲要在Variables顯示類的有關信息),提前執行了toString方法
本人親測,在toString()添加int i=1/0後出現異常.導致schemaMappings沒值
*/
public PluggableSchemaResolver(@Nullable ClassLoader classLoader) {
this.classLoader = classLoader;
this.schemaMappingsLocation = DEFAULT_SCHEMA_MAPPINGS_LOCATION;
}
/*
加載註冊bean,並返回加載個數
*/
public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
//記錄統計前BeanDefinition加載個數
int countBefore = getRegistry().getBeanDefinitionCount();
//加載以及註冊bean
documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
//記錄本次加載BeanDefinition個數
return getRegistry().getBeanDefinitionCount() - countBefore;
}
/*
創建閱讀器的上下文
*/
public XmlReaderContext createReaderContext(Resource resource) {
return new XmlReaderContext(resource,
//顯示出快速失敗 遇到錯誤時的行爲,就拋異常的
this.problemReporter,
//觀察者模式,當涉及註冊完成,以及別名註冊通知相關監聽者
this.eventListener,
//源提取器,封裝一些如Element等元素的
this.sourceExtractor,
this,
//命名空間處理器
getNamespaceHandlerResolver());
}
/*
創建BeanDefinition實際解析的委託對象,內部會解析beans一些默認參數,後續設置到BeanDefinition中
處理profile屬性
解析前處理,留給子類實現
解析
解析後處理,留給子類實現
this.delegate重置回其原始(父)引用
*/
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.
//創建BeanDefinition實際解析的委託對象
BeanDefinitionParserDelegate parent = this.delegate;
this.delegate = createDelegate(getReaderContext(), root, parent);
if (this.delegate.isDefaultNamespace(root)) {
//處理profile屬性
//<beans profile=“dev”>分別根據環境變量設置的值,從而選擇加載不同的beans,相當於部署不同的生產測試環境
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);
//解析後處理,留給子類實現
postProcessXml(root);
this.delegate = parent;
}
/*
當屬於默認命名空間時
遍歷root子元素
屬於默認命名空間:對bean處理
否則:對自定義命名空間的bean的處理
不屬於時對自定義命名空間的bean的處理
*/
protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
//對beans的處理
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)) {
//對bean的處理
parseDefaultElement(ele, delegate);
}
else {
//對自定義命名空間的bean的處理
delegate.parseCustomElement(ele);
}
}
}
}
else {
//對自定義命名空間的bean的處理
delegate.parseCustomElement(root);
}
}
/*
對import標籤的處理
對alias標籤的處理
對bean標籤的處理
對beans標籤的處理
*/
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//對import標籤的處理
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
//<import resource="XX">
importBeanDefinitionResource(ele);
}
//對alias標籤的處理
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
//<alias name="" alias="A,B,C">
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);
}
}
/*
解析BeanDefinitionElement,生成的dbHolder包含配置文件中配置的各種屬性,如class,name,id之類的屬性
若存在默認標籤的子節點下再有自定義屬性,則再次對自定義標籤解析
發出響應事件,通知相關監聽器,這個bean已經加載完成
*/
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
//dbHolder包含配置文件中配置的各種屬性,如class,name,id之類的屬性
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
//若存在默認標籤的子節點下再有自定義屬性,則再次對自定義標籤解析
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// Register the final decorated instance.
//對解析後的dbHolder進行註冊
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error("Failed to register bean definition with name '" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
//發出響應事件,通知相關監聽器,這個bean已經加載完成
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
/*
解析id
解析name
分割name屬性,添加別名
如果別名有值,而id沒有值,則從別名中拿出第一個賦值給beanName,且刪除別名裏面拿出來的值
校驗別名是否重複
解析其他複雜屬性,封裝到GenericBeanDefinition中
檢查bean沒有name則
根據spring命名規則爲當前bean生成對應的beanName
org.example.MyBeanTest#0 類名#循環次數
類名沒有被使用,則存儲成別名
將別名,beanName,beanDefinition封裝到BeanDefinitionHolder中
*/
@Nullable
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
//解析id
String id = ele.getAttribute(ID_ATTRIBUTE);
//解析name
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
//分割name屬性,添加別名
List<String> aliases = new ArrayList<>();
if (StringUtils.hasLength(nameAttr)) {
String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
//如果別名有值,而id沒有值,則從別名中拿出第一個賦值給beanName,且刪除別名裏面拿出來的值
String beanName = id;
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");
}
}
//校驗別名是否重複
if (containingBean == null) {
checkNameUniqueness(beanName, aliases, ele);
}
//解析其他複雜屬性,封裝到GenericBeanDefinition中
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {
if (!StringUtils.hasText(beanName)) {
try {
//如果不存在beanName,根據spring命名規則爲當前bean生成對應的beanName
if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(
beanDefinition, this.readerContext.getRegistry(), true);
}
else {
//org.example.MyBeanTest#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);
//封裝到BeanDefinitionHolder中
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
/**
* Validate that the specified bean name and aliases have not been used already
* within the current level of beans element nesting.
*/
protected void checkNameUniqueness(String beanName, List<String> aliases, Element beanElement) {
String foundName = null;
//查看存在重複名
if (StringUtils.hasText(beanName) && this.usedNames.contains(beanName)) {
foundName = beanName;
}
//如果不存在重複名,則遍歷查找所有別名是否重複
if (foundName == null) {
foundName = CollectionUtils.findFirstMatch(this.usedNames, aliases);
}
//存在重複名異常
if (foundName != null) {
error("Bean name '" + foundName + "' is already used in this <beans> element", beanElement);
}
//添加別名
this.usedNames.add(beanName);
this.usedNames.addAll(aliases);
}
/*
獲取className
className沒有
generatedBeanName=取父類名+$child,如果沒有
generatedBeanName=取獲取工廠bean+$created
查看是否是內部bean
generatedBeanName + # + hex
generatedBeanName + # + 循環次數
*/
public static String generateBeanName(
BeanDefinition definition, BeanDefinitionRegistry registry, boolean isInnerBean)
throws BeanDefinitionStoreException {
//獲取class構造名子
String generatedBeanName = definition.getBeanClassName();
if (generatedBeanName == null) {
//獲取父類創建名
if (definition.getParentName() != null) {
generatedBeanName = definition.getParentName() + "$child";
} else if (definition.getFactoryBeanName() != null) {
//獲取工廠bean創建名
generatedBeanName = definition.getFactoryBeanName() + "$created";
}
}
if (!StringUtils.hasText(generatedBeanName)) {
throw new BeanDefinitionStoreException("Unnamed bean definition specifies neither " +
"'class' nor 'parent' nor 'factory-bean' - can't generate bean name");
}
String id = generatedBeanName;
//查看是否是內部bean
if (isInnerBean) {
// Inner bean: generate identity hashcode suffix.
//class+#+hex
id = generatedBeanName + GENERATED_BEAN_NAME_SEPARATOR + ObjectUtils.getIdentityHexString(definition);
} else {
// Top-level bean: use plain class name with unique suffix if necessary.
//生成唯一bean,org.example.MyBeanTest#0 類名#循環次數
return uniqueBeanName(generatedBeanName, registry);
}
return id;
}
/*
入棧,解析過程中,跟蹤邏輯位置.toString()還能以樹狀視圖打印信息
解析class
解析parent
創建BeanDefinition本質是GenericBeanDefinition
硬編碼解析默認bean的各種屬性
提取description
解析元數據
解析lookup-method屬性,動態將抽象類的抽象方法替換爲某個子類的實現
解析replace-method屬性,可以動態替換返回實體bean,還能修改原有方法的邏輯
解析構造函數
解析Property子元素
解析Qualifier子元素
保存資源以及元素
出棧
*/
@Nullable
public AbstractBeanDefinition parseBeanDefinitionElement(
Element ele, String beanName, @Nullable BeanDefinition containingBean) {
//解析過程中,跟蹤邏輯位置.toString()還能以樹狀視圖打印信息
this.parseState.push(new BeanEntry(beanName));
String className = null;
//解析class屬性
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {
className = ele.getAttribute(CLASS_ATTRIBUTE).trim();
}
String parent = null;
//解析parent
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {
parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
//創建BeanDefinition本質是GenericBeanDefinition
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
//硬編碼解析默認bean的各種屬性
parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
//提取description
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
//解析元數據
parseMetaElements(ele, bd);
//解析lookup-method屬性,動態將抽象類的抽象方法替換爲某個子類的實現
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//解析replace-method屬性,可以動態替換返回實體bean,還能修改原有方法的邏輯
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//解析構造函數
parseConstructorArgElements(ele, bd);
//解析Property子元素
parsePropertyElements(ele, bd);
//解析Qualifier子元素
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;
}
/*
解析scope
解析abstract
解析lazy-init
解析autowire
...
*/
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
@Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {
//校驗是否是單例對象,singleton屬性升級到scope了
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));
}
//繼承父類的scope,如果子類沒有
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)));
}
String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
//解析lazy-init
if (isDefaultValue(lazyInit)) {
lazyInit = this.defaults.getLazyInit();
}
bd.setLazyInit(TRUE_VALUE.equals(lazyInit));
//解析autowire
String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
bd.setAutowireMode(getAutowireMode(autowire));
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 (isDefaultValue(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));
}
if (ele.hasAttribute(PRIMARY_ATTRIBUTE)) {
bd.setPrimary(TRUE_VALUE.equals(ele.getAttribute(PRIMARY_ATTRIBUTE)));
}
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);
}
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);
}
if (ele.hasAttribute(FACTORY_METHOD_ATTRIBUTE)) {
bd.setFactoryMethodName(ele.getAttribute(FACTORY_METHOD_ATTRIBUTE));
}
if (ele.hasAttribute(FACTORY_BEAN_ATTRIBUTE)) {
bd.setFactoryBeanName(ele.getAttribute(FACTORY_BEAN_ATTRIBUTE));
}
return bd;
}
/*
遍歷子元素
校驗node
封裝對象存儲
*/
public void parseMetaElements(Element ele, BeanMetadataAttributeAccessor attributeAccessor) {
/*
<bean>
<meta key ="" value ="">
<meta key ="" value ="">
</bean>
*/
//獲取當前節點所有子元素
NodeList nl = ele.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
//node是Element同時(是默認名稱空間|父節點不是默認名稱空間)且node節點名稱匹配meta
if (isCandidateElement(node) && nodeNameEquals(node, META_ELEMENT)) {
Element metaElement = (Element) node;
String key = metaElement.getAttribute(KEY_ATTRIBUTE);
String value = metaElement.getAttribute(VALUE_ATTRIBUTE);
BeanMetadataAttribute attribute = new BeanMetadataAttribute(key, value);
attribute.setSource(extractSource(metaElement));
attributeAccessor.addMetadataAttribute(attribute);
}
}
}
/*
<replaced-method name="computeValue" replacer="replacementComputeValue">
<arg-type>String</arg-type>
</replaced-method>
遍歷子元素
校驗node
構造ReplaceOverride
循環匹配arg-type,也就是方法所對應的參數類型,添加到ReplaceOverride
賦值
*/
public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) {
NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
//僅當在spring默認bean的子元素下,且標籤名爲<replaced-method>纔有效
if (isCandidateElement(node) && nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) {
Element replacedMethodEle = (Element) node;
//提取要替換的方法
String name = replacedMethodEle.getAttribute(NAME_ATTRIBUTE);
//提取對應的新的替換方法
String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE);
ReplaceOverride replaceOverride = new ReplaceOverride(name, callback);
// Look for arg-type match elements.
//循環匹配arg-type,也就是方法所對應的參數類型
List<Element> argTypeEles = DomUtils.getChildElementsByTagName(replacedMethodEle, ARG_TYPE_ELEMENT);
for (Element argTypeEle : argTypeEles) {
//記錄參數
String match = argTypeEle.getAttribute(ARG_TYPE_MATCH_ATTRIBUTE);
match = (StringUtils.hasText(match) ? match : DomUtils.getTextValue(argTypeEle));
if (StringUtils.hasText(match)) {
replaceOverride.addTypeIdentifier(match);
}
}
replaceOverride.setSource(extractSource(replacedMethodEle));
overrides.addOverride(replaceOverride);
}
}
}
/*
遍歷所有構造
解析構造
*/
public void parseConstructorArgElements(Element beanEle, BeanDefinition bd) {
NodeList nl = beanEle.getChildNodes();
//解析所有構造函數
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, CONSTRUCTOR_ARG_ELEMENT)) {
//解析構造函數
parseConstructorArgElement((Element) node, bd);
}
}
}
/*
獲取index,type,name
判斷是否有索引
有
入棧
解析ele對應的屬性元素
賦type,name值
校驗是否重複索引存儲
添加IndexedArgumentValue
出棧
無
入棧
解析ele對應的屬性元素
賦type,name值
添加GenericArgumentValues中
出棧
*/
public void parseConstructorArgElement(Element ele, BeanDefinition bd) {
//獲取index,type,name
String indexAttr = ele.getAttribute(INDEX_ATTRIBUTE);
String typeAttr = ele.getAttribute(TYPE_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
if (StringUtils.hasLength(indexAttr)) {
try {
int index = Integer.parseInt(indexAttr);
if (index < 0) {
error("'index' cannot be lower than 0", ele);
}
else {
try {
this.parseState.push(new ConstructorArgumentEntry(index));
//解析ele對應的屬性元素
Object value = parsePropertyValue(ele, bd, null);
ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value);
if (StringUtils.hasLength(typeAttr)) {
valueHolder.setType(typeAttr);
}
if (StringUtils.hasLength(nameAttr)) {
valueHolder.setName(nameAttr);
}
valueHolder.setSource(extractSource(ele));
//不允許重複指定相同參數
if (bd.getConstructorArgumentValues().hasIndexedArgumentValue(index)) {
error("Ambiguous constructor-arg entries for index " + index, ele);
}
else {
//添加IndexedArgumentValues中
bd.getConstructorArgumentValues().addIndexedArgumentValue(index, valueHolder);
}
}
finally {
this.parseState.pop();
}
}
}
catch (NumberFormatException ex) {
error("Attribute 'index' of tag 'constructor-arg' must be an integer", ele);
}
}
//沒有設置index,則自動尋找
else {
try {
this.parseState.push(new ConstructorArgumentEntry());
Object value = parsePropertyValue(ele, bd, null);
ConstructorArgumentValues.ValueHolder valueHolder = new ConstructorArgumentValues.ValueHolder(value);
if (StringUtils.hasLength(typeAttr)) {
valueHolder.setType(typeAttr);
}
if (StringUtils.hasLength(nameAttr)) {
valueHolder.setName(nameAttr);
}
valueHolder.setSource(extractSource(ele));
//添加GenericArgumentValues中
bd.getConstructorArgumentValues().addGenericArgumentValue(valueHolder);
}
finally {
this.parseState.pop();
}
}
}
/*
校驗屬性,一個屬性只能對應一種類型,ref,value,list等
判斷ref和value屬性是否有重複
ref封裝RuntimeBeanReference
value封裝TypedStringValue
解析子元素
*/
public Object parsePropertyValue(Element ele, BeanDefinition bd, @Nullable String propertyName) {
String elementName = (propertyName != null ?
"<property> element for property '" + propertyName + "'" :
"<constructor-arg> element");
// Should only have one child element: ref, value, list, etc.
//一個屬性只能對應一種類型,ref,value,list等
NodeList nl = ele.getChildNodes();
Element subElement = null;
for (int i = 0; i < nl.getLength(); i++) {
Node node = nl.item(i);
//對應description和meta不處理
if (node instanceof Element && !nodeNameEquals(node, DESCRIPTION_ELEMENT) &&
!nodeNameEquals(node, META_ELEMENT)) {
// Child element is what we're looking for.
if (subElement != null) {
error(elementName + " must not contain more than one sub-element", ele);
}
else {
subElement = (Element) node;
}
}
}
//判斷ref和value屬性是否有重複
boolean hasRefAttribute = ele.hasAttribute(REF_ATTRIBUTE);
boolean hasValueAttribute = ele.hasAttribute(VALUE_ATTRIBUTE);
//同時存在ref和value,或者有ref或者value且有子元素則異常
if ((hasRefAttribute && hasValueAttribute) ||
((hasRefAttribute || hasValueAttribute) && subElement != null)) {
error(elementName +
" is only allowed to contain either 'ref' attribute OR 'value' attribute OR sub-element", ele);
}
//ref封裝RuntimeBeanReference
if (hasRefAttribute) {
String refName = ele.getAttribute(REF_ATTRIBUTE);
if (!StringUtils.hasText(refName)) {
error(elementName + " contains empty 'ref' attribute", ele);
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName);
ref.setSource(extractSource(ele));
return ref;
}
//value封裝TypedStringValue
else if (hasValueAttribute) {
TypedStringValue valueHolder = new TypedStringValue(ele.getAttribute(VALUE_ATTRIBUTE));
valueHolder.setSource(extractSource(ele));
return valueHolder;
}
//解析子元素
else if (subElement != null) {
return parsePropertySubElement(subElement, bd);
}
//啥都沒有異常
else {
// Neither child element nor "ref" or "value" attribute found.
error(elementName + " must specify a ref or value", ele);
return null;
}
}
/*
子元素不是默認名稱空間,則採用自定義解析器解析
嵌套bean的處理
使用默認標籤解析
存在默認標籤的子節點下再有自定義屬性,則再次對自定義標籤解析
ref處理
bean爲空則對父上下文中另一個bean的id的引用。
對value子元素解析
對null子元素解析
對集合,props解析
...
*/
public Object parsePropertySubElement(Element ele, @Nullable BeanDefinition bd, @Nullable String defaultValueType) {
//子元素不是默認名稱空間,則採用自定義解析器解析
if (!isDefaultNamespace(ele)) {
return parseNestedCustomElement(ele, bd);
}
//嵌套bean的處理
else if (nodeNameEquals(ele, BEAN_ELEMENT)) {
//使用默認標籤解析
BeanDefinitionHolder nestedBd = parseBeanDefinitionElement(ele, bd);
if (nestedBd != null) {
//存在默認標籤的子節點下再有自定義屬性,則再次對自定義標籤解析
nestedBd = decorateBeanDefinitionIfRequired(ele, nestedBd, bd);
}
return nestedBd;
}
//ref處理
else if (nodeNameEquals(ele, REF_ELEMENT)) {
// A generic reference to any name of any bean.
String refName = ele.getAttribute(BEAN_REF_ATTRIBUTE);
boolean toParent = false;
if (!StringUtils.hasLength(refName)) {
// A reference to the id of another bean in a parent context.
//對父上下文中另一個bean的id的引用。
refName = ele.getAttribute(PARENT_REF_ATTRIBUTE);
toParent = true;
if (!StringUtils.hasLength(refName)) {
error("'bean' or 'parent' is required for <ref> element", ele);
return null;
}
}
if (!StringUtils.hasText(refName)) {
error("<ref> element contains empty target attribute", ele);
return null;
}
RuntimeBeanReference ref = new RuntimeBeanReference(refName, toParent);
ref.setSource(extractSource(ele));
return ref;
}
else if (nodeNameEquals(ele, IDREF_ELEMENT)) {
return parseIdRefElement(ele);
}
else if (nodeNameEquals(ele, VALUE_ELEMENT)) {
return parseValueElement(ele, defaultValueType);
}
//對null子元素解析
else if (nodeNameEquals(ele, NULL_ELEMENT)) {
// It's a distinguished null value. Let's wrap it in a TypedStringValue
// object in order to preserve the source location.
TypedStringValue nullHolder = new TypedStringValue(null);
nullHolder.setSource(extractSource(ele));
return nullHolder;
}
else if (nodeNameEquals(ele, ARRAY_ELEMENT)) {
return parseArrayElement(ele, bd);
}
else if (nodeNameEquals(ele, LIST_ELEMENT)) {
return parseListElement(ele, bd);
}
else if (nodeNameEquals(ele, SET_ELEMENT)) {
return parseSetElement(ele, bd);
}
else if (nodeNameEquals(ele, MAP_ELEMENT)) {
return parseMapElement(ele, bd);
}
else if (nodeNameEquals(ele, PROPS_ELEMENT)) {
return parsePropsElement(ele);
}
else {
error("Unknown property sub-element: [" + ele.getNodeName() + "]", ele);
return null;
}
}
/*
獲取節點上的所有屬性
遍歷此節點所有的屬性,查看是否有適用於修飾的屬性
遍歷所有的子節點,查看是否有適用於修飾的子節點
*/
public BeanDefinitionHolder decorateBeanDefinitionIfRequired(
Element ele, BeanDefinitionHolder originalDef, @Nullable BeanDefinition containingBd) {
BeanDefinitionHolder finalDefinition = originalDef;
// Decorate based on custom attributes first.
//獲取節點上的所有屬性
NamedNodeMap attributes = ele.getAttributes();
//遍歷此節點所有的屬性,查看是否有適用於修飾的屬性
for (int i = 0; i < attributes.getLength(); i++) {
Node node = attributes.item(i);
finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
}
// Decorate based on custom nested elements.
NodeList children = ele.getChildNodes();
//遍歷所有的子節點,查看是否有適用於修飾的子節點
for (int i = 0; i < children.getLength(); i++) {
Node node = children.item(i);
//node是否是element元素
if (node.getNodeType() == Node.ELEMENT_NODE) {
finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
}
}
return finalDefinition;
}
/*
使用beanName做唯一標識註冊
註冊所有別名
*/
public static void registerBeanDefinition(
BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
//使用beanName做唯一標識註冊
// 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);
}
}
}
/*
註冊前最後一次校驗
如果beanName已經註冊,且配置了不允許覆蓋,則拋出異常
註冊beanDefinition
記錄beanName
刪除緩存
*/
@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 {
/*
註冊前最後一次校驗,主要對於methodOverrides校驗
校驗是否與工廠方法並存或者methodOverrides方法不存在
*/
((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) {
//如果beanName已經註冊,且配置了不允許覆蓋,則拋出異常
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 + "]");
}
}
//註冊beanDefinition
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {
if (hasBeanCreationStarted()) {
// Cannot modify startup-time collection elements anymore (for stable iteration)
//不能修改正在創建狀態中的集合元素,用於穩定迭代,擴容數+1
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
//記錄beanName
this.beanDefinitionMap.put(beanName, beanDefinition);
this.beanDefinitionNames.add(beanName);
removeManualSingletonName(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
//刪除緩存
resetBeanDefinition(beanName);
}
//是否處於凍結狀態,
//凍結後,註冊的bean定義將不被修改或任何進一步的處理
else if (isConfigurationFrozen()) {
clearByTypeCache();
}
}
對alias標籤的處理
/*
對別名和name的檢測
註冊
*/
protected void processAliasRegistration(Element ele) {
String name = ele.getAttribute(NAME_ATTRIBUTE);
String alias = ele.getAttribute(ALIAS_ATTRIBUTE);
boolean valid = true;
if (!StringUtils.hasText(name)) {
getReaderContext().error("Name must not be empty", ele);
valid = false;
}
if (!StringUtils.hasText(alias)) {
getReaderContext().error("Alias must not be empty", ele);
valid = false;
}
if (valid) {
try {
getReaderContext().getRegistry().registerAlias(name, alias);
}
catch (Exception ex) {
getReaderContext().error("Failed to register alias '" + alias +
"' for bean with name '" + name + "'", ele, ex);
}
getReaderContext().fireAliasRegistered(name, alias, extractSource(ele));
}
}
/*
如果alias與beanName相同,則不記錄alias,且刪除對應alias
否則
獲取別名緩存
是否允許覆蓋
alias不允許覆蓋,則異常
alias循環檢查,當A->B,B->C,再次出現A->C則異常
緩存
*/
@Override
public void registerAlias(String name, String alias) {
Assert.hasText(name, "'name' must not be empty");
Assert.hasText(alias, "'alias' must not be empty");
//併發容器,所以加鎖
synchronized (this.aliasMap) {
//如果alias與beanName相同,則不記錄alias,且刪除對應alias
if (alias.equals(name)) {
this.aliasMap.remove(alias);
if (logger.isDebugEnabled()) {
logger.debug("Alias definition '" + alias + "' ignored since it points to same name");
}
}
else {
String registeredName = this.aliasMap.get(alias);
if (registeredName != null) {
if (registeredName.equals(name)) {
// An existing alias - no need to re-register
return;
}
//alias不允許覆蓋,則異常
if (!allowAliasOverriding()) {
throw new IllegalStateException("Cannot define alias '" + alias + "' for name '" +
name + "': It is already registered for name '" + registeredName + "'.");
}
if (logger.isDebugEnabled()) {
logger.debug("Overriding alias '" + alias + "' definition for registered name '" +
registeredName + "' with new target name '" + name + "'");
}
}
//alias循環檢查,當A->B,B->C,再次出現A->C則異常
checkForAliasCircle(name, alias);
this.aliasMap.put(alias, name);
if (logger.isTraceEnabled()) {
logger.trace("Alias definition '" + alias + "' registered for name '" + name + "'");
}
}
}
}
對import處理
/*
獲取路徑
解析系統屬性如${user.dir}
判斷url是相對還是絕對
絕對,直接加載配置文件
根據相對地址算出絕對地址
解析
解析不成功,採用默認解析器
監聽激活處理
*/
protected void importBeanDefinitionResource(Element ele) {
//獲取resource
String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
if (!StringUtils.hasText(location)) {
getReaderContext().error("Resource location must not be empty", ele);
return;
}
// Resolve system properties: e.g. "${user.dir}"
//解析系統屬性如${user.dir}
location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);
Set<Resource> actualResources = new LinkedHashSet<>(4);
// Discover whether the location is an absolute or relative URI
//判斷url是相對還是絕對
boolean absoluteLocation = false;
try {
absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
}
catch (URISyntaxException ex) {
// cannot convert to an URI, considering the location relative
// unless it is the well-known Spring prefix "classpath*:"
}
// Absolute or relative?
//絕對,直接加載配置文件
if (absoluteLocation) {
try {
//XmlBeanDefinitionReader.loadBeanDefinitions(Resource)
int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
if (logger.isTraceEnabled()) {
logger.trace("Imported " + importCount + " bean definitions from URL location [" + location + "]");
}
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from URL location [" + location + "]", ele, ex);
}
}
else {
// No URL -> considering resource location as relative to the current file.
//根據相對地址算出絕對地址
try {
int importCount;
//Resource存在多個子實現類,如VFS,File等,每個createRelative方式實現不一樣,所以先試用子類方法嘗試解析
Resource relativeResource = getReaderContext().getResource().createRelative(location);
if (relativeResource.exists()) {
//這裏使用了策略模式,每個子類生成的ReaderContext都不同,然後讓ReaderContext調用的loadBeanDefinitions也不同
importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
actualResources.add(relativeResource);
}
else {
//解析不成功,採用默認解析器
String baseLocation = getReaderContext().getResource().getURL().toString();
importCount = getReaderContext().getReader().loadBeanDefinitions(
StringUtils.applyRelativePath(baseLocation, location), actualResources);
}
if (logger.isTraceEnabled()) {
logger.trace("Imported " + importCount + " bean definitions from relative location [" + location + "]");
}
}
catch (IOException ex) {
getReaderContext().error("Failed to resolve current resource location", ele, ex);
}
catch (BeanDefinitionStoreException ex) {
getReaderContext().error(
"Failed to import bean definitions from relative location [" + location + "]", ele, ex);
}
}
Resource[] actResArray = actualResources.toArray(new Resource[0]);
//監聽激活處理
getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}
對自定義命名空間的bean的處理
/*
獲取所有已經配置的handler映射,讀取配置文件
根據命名空間找到對應的信息
當是類的時候說明,已經做過解析直接緩存讀取,直接返回
沒有做過解析,返回類路徑
判斷handlerClass是否是NamespaceHandler子類
初始化類
調用自定義的namespaceHandler的初始化方法,這個時候注入瞭解析器
記錄在緩存
返回
*/
public NamespaceHandler resolve(String namespaceUri) {
//獲取所有已經配置的handler映射,讀取配置文件
//和類org.springframework.beans.factory.xml.PluggableSchemaResolver.getSchemaMappings一樣,不在闡述
Map<String, Object> handlerMappings = getHandlerMappings();
//根據命名空間找到對應的信息
Object handlerOrClassName = handlerMappings.get(namespaceUri);
if (handlerOrClassName == null) {
return null;
}
//這個時候還是字符串
else if (handlerOrClassName instanceof NamespaceHandler) {
//已經做過解析,直接緩存讀取
return (NamespaceHandler) handlerOrClassName;
}
else {
//沒有做過解析,返回類路徑
String className = (String) handlerOrClassName;
try {
Class<?> handlerClass = ClassUtils.forName(className, this.classLoader);
//判斷handlerClass是否是NamespaceHandler子類
if (!NamespaceHandler.class.isAssignableFrom(handlerClass)) {
throw new FatalBeanException("Class [" + className + "] for namespace [" + namespaceUri +
"] does not implement the [" + NamespaceHandler.class.getName() + "] interface");
}
//初始化類
NamespaceHandler namespaceHandler = (NamespaceHandler) BeanUtils.instantiateClass(handlerClass);
//調用自定義的namespaceHandler的初始化方法,這個時候注入瞭解析器
namespaceHandler.init();
//記錄在緩存
handlerMappings.put(namespaceUri, namespaceHandler);
return namespaceHandler;
}
catch (ClassNotFoundException ex) {
throw new FatalBeanException("Could not find NamespaceHandler class [" + className +
"] for namespace [" + namespaceUri + "]", ex);
}
catch (LinkageError err) {
throw new FatalBeanException("Unresolvable class definition for NamespaceHandler class [" +
className + "] for namespace [" + namespaceUri + "]", err);
}
}
}
/**
* 本人自定義DTD格式解析
* @author ****
* @create *****
*/
public class MyNamespaceHandler extends NamespaceHandlerSupport {
public void init() {
//user對應配置文件
// <myname:user id="testBean" username="aaa" email="bbb"></myname:user>
registerBeanDefinitionParser("user", new UserBeanDefinitionParser());
}
}
@Override
@Nullable
public BeanDefinition parse(Element element, ParserContext parserContext) {
//尋找解析器並進行解析操作
BeanDefinitionParser parser = findParserForElement(element, parserContext);
//AbstractBeanDefinitionParser.parse
return (parser != null ? parser.parse(element, parserContext) : null);
}
/*
獲取元素名稱
根據user獲取解析器
*/
private BeanDefinitionParser findParserForElement(Element element, ParserContext parserContext) {
//獲取元素名稱,也就是<myname:user>中的user
String localName = parserContext.getDelegate().getLocalName(element);
//根據user獲取解析器,也就是在registerBeanDefinitionParser("user", new UserBeanDefinitionParser()
BeanDefinitionParser parser = this.parsers.get(localName);
if (parser == null) {
parserContext.getReaderContext().fatal(
"Cannot locate BeanDefinitionParser for element [" + localName + "]", element);
}
return parser;
}
/*
調用自定義的解析器類
對id的支持
對name別名註冊的支持
將AbstractBeanDefinition轉換爲BeanDefinitionHolder並註冊
註冊別名
子類後續處理
通知監聽器,註冊完成
*/
public final BeanDefinition parse(Element element, ParserContext parserContext) {
//內部調用了自定義的解析器類
AbstractBeanDefinition definition = parseInternal(element, parserContext);
if (definition != null && !parserContext.isNested()) {
try {
//對id的支持,當沒id的時候,使用內部構造名字
String id = resolveId(element, definition, parserContext);
if (!StringUtils.hasText(id)) {
parserContext.getReaderContext().error(
"Id is required for element '" + parserContext.getDelegate().getLocalName(element)
+ "' when used as a top-level tag", element);
}
//對name別名註冊的支持
String[] aliases = null;
if (shouldParseNameAsAliases()) {
String name = element.getAttribute(NAME_ATTRIBUTE);
if (StringUtils.hasLength(name)) {
aliases = StringUtils.trimArrayElements(StringUtils.commaDelimitedListToStringArray(name));
}
}
//將AbstractBeanDefinition轉換爲BeanDefinitionHolder並註冊
BeanDefinitionHolder holder = new BeanDefinitionHolder(definition, id, aliases);
//註冊別名以及名字,還有BeanDefinition
registerBeanDefinition(holder, parserContext.getRegistry());
if (shouldFireEvents()) {
//需要通知監聽器則進行處理
BeanComponentDefinition componentDefinition = new BeanComponentDefinition(holder);
//子類後續處理
postProcessComponentDefinition(componentDefinition);
//通知監聽器,註冊完成
parserContext.registerComponent(componentDefinition);
}
}
catch (BeanDefinitionStoreException ex) {
String msg = ex.getMessage();
parserContext.getReaderContext().error((msg != null ? msg : ex.toString()), element);
return null;
}
}
return definition;
}
/*
獲取自定義標籤解析器中的class
若沒有獲取class,則獲取beanClassName
繼承父類scope
配置延遲加載
調用自定義的解析方法
*/
protected final AbstractBeanDefinition parseInternal(Element element, ParserContext parserContext) {
//內部構造了GenericBeanDefinition
BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition();
String parentName = getParentName(element);
if (parentName != null) {
builder.getRawBeanDefinition().setParentName(parentName);
}
//獲取自定義標籤解析器中的class,此時會調用UserBeanDefinitionParser.getBeanClass
/*
org.example.custom.dtd.UserBeanDefinitionParser.getBeanClass
*/
Class<?> beanClass = getBeanClass(element);
if (beanClass != null) {
builder.getRawBeanDefinition().setBeanClass(beanClass);
} else {
//若子類沒有重寫,則嘗試子類是否重寫了getBeanClassName方法
String beanClassName = getBeanClassName(element);
if (beanClassName != null) {
builder.getRawBeanDefinition().setBeanClassName(beanClassName);
}
}
builder.getRawBeanDefinition().setSource(parserContext.extractSource(element));
BeanDefinition containingBd = parserContext.getContainingBeanDefinition();
//繼承父類scope
if (containingBd != null) {
// Inner bean definition must receive same scope as containing bean.
builder.setScope(containingBd.getScope());
}
//配置延遲加載
if (parserContext.isDefaultLazyInit()) {
// Default-lazy-init applies to custom bean definitions as well.
builder.setLazyInit(true);
}
//調用子類重寫的方法解析,這裏調用了自定義的解析方法
doParse(element, parserContext, builder);
//內部做了loopup-method,replace-method,factory-method覆蓋方法的校驗
return builder.getBeanDefinition();
}