/*
这里分别使用
装饰者模式:使用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();
}