共计 19063 个字符,预计需要花费 48 分钟才能阅读完成。
1. 默认标签判断类型别离解析
- import
- alias
- bean(重点)
- beans
// 默认标签解析
private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
//import 标签解析 重要水平 1,可看可不看
if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {importBeanDefinitionResource(ele);
}
//alias 标签解析 别名标签 重要水平 1,可看可不看
else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {processAliasRegistration(ele);
}
//bean 标签,重要水平 5,必须看
else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {processBeanDefinition(ele, delegate);
}
else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
// recurse
doRegisterBeanDefinitions(ele);
}
}
2. 默认标签 bean 元素的解析
//bean 标签解析
protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
// 重点看这个办法,重要水平 5,解析 document,封装成 BeanDefinition
BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
if (bdHolder != null) {
// 该办法性能不重要,设计模式重点看一下,装璜者设计模式,加上 SPI 设计思维
bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
try {
// 实现 document 到 BeanDefinition 对象转换后,对 BeanDefinition 对象进行缓存注册
// Register the final decorated instance.
BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
}
catch (BeanDefinitionStoreException ex) {getReaderContext().error("Failed to register bean definition with name'" +
bdHolder.getBeanName() + "'", ele, ex);
}
// Send registration event.
getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
}
}
3. BeanDefinitionParserDelegate 解析 document,封装成 BeanDefinition
public BeanDefinitionHolder parseBeanDefinitionElement(Element ele, @Nullable BeanDefinition containingBean) {
// bean 元素的属性 id、name(别名,能够配置多个 以,; 分隔)String id = ele.getAttribute(ID_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
List<String> aliases = new ArrayList<>();
if (StringUtils.hasLength(nameAttr)) {String[] nameArr = StringUtils.tokenizeToStringArray(nameAttr, MULTI_VALUE_ATTRIBUTE_DELIMITERS);
aliases.addAll(Arrays.asList(nameArr));
}
// id 就是 bean 的名称,如果 id 没有配置,然而 name 配置了,就应用 name 的值作为 bean 的名称
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");
}
}
// 查看 beanName 是否反复
if (containingBean == null) {
// 查看配置的 beanName 和别名是否惟一,之前是否有 bean 曾经应用了这个名称
checkNameUniqueness(beanName, aliases, ele);
}
// 解析并创立 beanDefinition 对象
// 最初解析实现后,把名称、类型以及值的信息封装到对象上,// 而后设置到 beanDefinition 对象上。// bean 元素解析实现,将属性设置到 beanDefinition 对象上,// 而后返回到上一步,封装到了 BeanDefinitionHolder 对象上保护
AbstractBeanDefinition beanDefinition = parseBeanDefinitionElement(ele, beanName, containingBean);
if (beanDefinition != null) {if (!StringUtils.hasText(beanName)) {
try {if (containingBean != null) {
beanName = BeanDefinitionReaderUtils.generateBeanName(beanDefinition, this.readerContext.getRegistry(), true);
}
else {beanName = this.readerContext.generateBeanName(beanDefinition);
// Register an alias for the plain bean class name, if still possible,
// if the generator returned the class name plus a suffix.
// This is expected for Spring 1.2/2.0 backwards compatibility.
String beanClassName = beanDefinition.getBeanClassName();
if (beanClassName != null &&
beanName.startsWith(beanClassName) && beanName.length() > beanClassName.length() &&
!this.readerContext.getRegistry().isBeanNameInUse(beanClassName)) {aliases.add(beanClassName);
}
}
if (logger.isTraceEnabled()) {
logger.trace("Neither XML'id'nor'name'specified -" +
"using generated bean name [" + beanName + "]");
}
}
catch (Exception ex) {error(ex.getMessage(), ele);
return null;
}
}
String[] aliasesArray = StringUtils.toStringArray(aliases);
return new BeanDefinitionHolder(beanDefinition, beanName, aliasesArray);
}
return null;
}
4. 解析 bean 元素的属性、子元素的次要逻辑都在这个办法外面:
public AbstractBeanDefinition parseBeanDefinitionElement(Element ele, String beanName, @Nullable BeanDefinition containingBean) {this.parseState.push(new BeanEntry(beanName));
String className = null;
if (ele.hasAttribute(CLASS_ATTRIBUTE)) {className = ele.getAttribute(CLASS_ATTRIBUTE).trim();}
String parent = null;
if (ele.hasAttribute(PARENT_ATTRIBUTE)) {parent = ele.getAttribute(PARENT_ATTRIBUTE);
}
try {
//1. 创立 GenericBeanDefinition 对象
AbstractBeanDefinition bd = createBeanDefinition(className, parent);
//2. 解析 bean 标签的属性,并把解析进去的属性设置到 BeanDefinition 对象中 (scope 等)(**********)parseBeanDefinitionAttributes(ele, beanName, containingBean, bd);
bd.setDescription(DomUtils.getChildElementValueByTagName(ele, DESCRIPTION_ELEMENT));
//3. 解析 bean 中的 meta 标签(参见 spring-xml)parseMetaElements(ele, bd);
//4. 解析 bean 中的 lookup-method 标签(代理,作用:多态形式)重要水平:2,可看可不看
parseLookupOverrideSubElements(ele, bd.getMethodOverrides());
//5. 解析 bean 中的 replaced-method 标签 重要水平:2,可看可不看
parseReplacedMethodSubElements(ele, bd.getMethodOverrides());
//6. 解析 bean 中的 constructor-arg 标签 重要水平:2,可看可不看
parseConstructorArgElements(ele, bd);
//7. 解析 bean 中的 property 标签 重要水平:2,可看可不看
parsePropertyElements(ele, bd);
//8. 解析 qualifier 能够不看,用不到
parseQualifierElements(ele, bd);
bd.setResource(this.readerContext.getResource());
bd.setSource(extractSource(ele));
return bd;
}
//catch 省略......
return null;
}
4.1 创立 beanDefinition 对象:
public static AbstractBeanDefinition createBeanDefinition(@Nullable String parentName, @Nullable String className, @Nullable ClassLoader classLoader) throws ClassNotFoundException {
// 创立 BeanDefinition 对象,并设置 beanClass 和 beanClassName 属性
GenericBeanDefinition bd = new GenericBeanDefinition();
bd.setParentName(parentName);
if (className != null) {if (classLoader != null) {bd.setBeanClass(ClassUtils.forName(className, classLoader));
}
else {bd.setBeanClassName(className);
}
}
return bd;
}
4.2 解析 bean 标签的属性,并把解析进去的属性设置到 BeanDefinition 对象中
public AbstractBeanDefinition parseBeanDefinitionAttributes(Element ele, String beanName,
@Nullable BeanDefinition containingBean, AbstractBeanDefinition bd) {if (ele.hasAttribute(SINGLETON_ATTRIBUTE)) {error("Old 1.x'singleton'attribute in use - upgrade to'scope'declaration", ele);
}
else if (ele.hasAttribute(SCOPE_ATTRIBUTE)) {bd.setScope(ele.getAttribute(SCOPE_ATTRIBUTE));
}
else if (containingBean != null) {
// Take default from containing bean in case of an inner bean definition.
bd.setScope(containingBean.getScope());
}
if (ele.hasAttribute(ABSTRACT_ATTRIBUTE)) {bd.setAbstract(TRUE_VALUE.equals(ele.getAttribute(ABSTRACT_ATTRIBUTE)));
}
String lazyInit = ele.getAttribute(LAZY_INIT_ATTRIBUTE);
if (DEFAULT_VALUE.equals(lazyInit)) {lazyInit = this.defaults.getLazyInit();
}
bd.setLazyInit(TRUE_VALUE.equals(lazyInit));
String autowire = ele.getAttribute(AUTOWIRE_ATTRIBUTE);
bd.setAutowireMode(getAutowireMode(autowire));
if (ele.hasAttribute(DEPENDS_ON_ATTRIBUTE)) {String dependsOn = ele.getAttribute(DEPENDS_ON_ATTRIBUTE);
bd.setDependsOn(StringUtils.tokenizeToStringArray(dependsOn, MULTI_VALUE_ATTRIBUTE_DELIMITERS));
}
// 这个属性有代码案例演示,请参看案例
String autowireCandidate = ele.getAttribute(AUTOWIRE_CANDIDATE_ATTRIBUTE);
if ("".equals(autowireCandidate) || DEFAULT_VALUE.equals(autowireCandidate)) {String candidatePattern = this.defaults.getAutowireCandidates();
if (candidatePattern != null) {String[] patterns = StringUtils.commaDelimitedListToStringArray(candidatePattern);
bd.setAutowireCandidate(PatternMatchUtils.simpleMatch(patterns, beanName));
}
}
else {bd.setAutowireCandidate(TRUE_VALUE.equals(autowireCandidate));
}
// 这个属性有代码案例演示,请参看案例
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;
}
4.3 解析 bean 中的 meta 标签(参见 spring-xml)
4.4 设置元数据,做一个标识解析 bean 中的 lookup-method 标签(代理,作用:多态形式)重要水平:2,可看可不看
public void parseLookupOverrideSubElements(Element beanEle, MethodOverrides overrides) {NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, LOOKUP_METHOD_ELEMENT)) {Element ele = (Element) node;
String methodName = ele.getAttribute(NAME_ATTRIBUTE);
String beanRef = ele.getAttribute(BEAN_ELEMENT);
LookupOverride override = new LookupOverride(methodName, beanRef);
override.setSource(extractSource(ele));
overrides.addOverride(override);
}
}
}
4.5 解析 bean 中的 replaced-method 标签 重要水平:2,可看可不看
public void parseReplacedMethodSubElements(Element beanEle, MethodOverrides overrides) {NodeList nl = beanEle.getChildNodes();
for (int i = 0; i < nl.getLength(); i++) {Node node = nl.item(i);
if (isCandidateElement(node) && nodeNameEquals(node, REPLACED_METHOD_ELEMENT)) {Element replacedMethodEle = (Element) node;
String name = replacedMethodEle.getAttribute(NAME_ATTRIBUTE);
String callback = replacedMethodEle.getAttribute(REPLACER_ATTRIBUTE);
// 一个 replaced-method 标签封装成一个 ReplaceOverride 对象,最初退出到 BeanDefinition 对象中
ReplaceOverride replaceOverride = new ReplaceOverride(name, callback);
// Look for arg-type match elements.
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);
}
}
}
4.6 解析 bean 中的 constructor-arg 标签,结构器注入
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);
}
}
}
public void parseConstructorArgElement(Element ele, BeanDefinition bd) {String indexAttr = ele.getAttribute(INDEX_ATTRIBUTE);
String typeAttr = ele.getAttribute(TYPE_ATTRIBUTE);
String nameAttr = ele.getAttribute(NAME_ATTRIBUTE);
// 蕴含 index 属性
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));
// 解析 value 值, 解析元素的 value 值,过程和解析 set 注入 property 的流程一样,// 而后封装到 valueHolder 对象中,// 最初把 index 和 valueHolder 设置到 beanDefinition 的 contructorArgumentValues 的属性上
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));
// 如果 index 索引反复,那么赋值时会报错
if (bd.getConstructorArgumentValues().hasIndexedArgumentValue(index)) {error("Ambiguous constructor-arg entries for index" + index, ele);
}
else {
// 把 index 与 valueHolder 封装到 ConstructorArgumentValues 对象,再把该对象设置到 bd 上
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));
// 会把 valueHolder 的值封装到 GenericArgumengValue 中
bd.getConstructorArgumentValues().addGenericArgumentValue(valueHolder);
}
finally {this.parseState.pop();
}
}
}
4.7 解析 bean 中 的 property 标签 (和结构相似)
4.8 解析 qualifier 能够不看,用不到
4.9 返回 BeanDefinition 对象
5.(承接第 4 点)该办法性能不重要,设计模式重点看一下,装璜者设计模式,加上 SPI 设计思维,将持有的 BeanDefinitionHolder 对象进行装璜
public BeanDefinitionHolder decorateBeanDefinitionIfRequired(Element ele, BeanDefinitionHolder definitionHolder, @Nullable BeanDefinition containingBd) {
BeanDefinitionHolder finalDefinition = definitionHolder;
// 依据 bean 标签属性装璜 BeanDefinitionHolder,比方 <bean class="xx" p:username="jack"/>
//
// 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);
}
// 依据 bean 标签子元素装璜 BeanDefinitionHolder
// Decorate based on custom nested elements.
NodeList children = ele.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {Node node = children.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE) {finalDefinition = decorateIfRequired(node, finalDefinition, containingBd);
}
}
return finalDefinition;
}
6. 装璜 BeanDefinitionHolder
public BeanDefinitionHolder decorateIfRequired(Node node, BeanDefinitionHolder originalDef, @Nullable BeanDefinition containingBd) {
// 依据 node 获取到 node 的命名空间,形如:http://www.springframework.org/schema/p
String namespaceUri = getNamespaceURI(node);
if (namespaceUri != null && !isDefaultNamespace(namespaceUri)) {
// 这里有 SPI 服务发现的思维,依据配置文件获取 namespaceUri 对应的解决类
NamespaceHandler handler = this.readerContext.getNamespaceHandlerResolver().resolve(namespaceUri);
if (handler != null) {
// 调用 NamespaceHandler 解决类的 decorate 办法,开始具体装璜过程,并返回装璜完的对象
BeanDefinitionHolder decorated =
handler.decorate(node, originalDef, new ParserContext(this.readerContext, this, containingBd));
if (decorated != null) {return decorated;}
}
// 略......
}
return originalDef;
}
spi 机制
public NamespaceHandler resolve(String namespaceUri) {
// 获取 spring 中所有 jar 包外面的 "META-INF/spring.handlers" 文件,并且建设映射关系
Map<String, Object> handlerMappings = getHandlerMappings();
// 依据 namespaceUri:http://www.springframework.org/schema/p,获取到这个命名空间的解决类
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);
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);
// 调用解决类的 init 办法,在 init 办法中实现标签元素解析类的注册 *** 重要
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);
}
}
}
private Map<String, Object> getHandlerMappings() {
Map<String, Object> handlerMappings = this.handlerMappings;
if (handlerMappings == null) {synchronized (this) {
handlerMappings = this.handlerMappings;
if (handlerMappings == null) {if (logger.isTraceEnabled()) {logger.trace("Loading NamespaceHandler mappings from [" + this.handlerMappingsLocation + "]");
}
try {
// 加载 "META-INF/spring.handlers" 文件过程
Properties mappings =
PropertiesLoaderUtils.loadAllProperties(this.handlerMappingsLocation, this.classLoader);
if (logger.isTraceEnabled()) {logger.trace("Loaded NamespaceHandler mappings:" + mappings);
}
// 所有 "META-INF/spring.handlers" 文件外面的内容建设映射关系
handlerMappings = new ConcurrentHashMap<>(mappings.size());
CollectionUtils.mergePropertiesIntoMap(mappings, handlerMappings);
this.handlerMappings = handlerMappings;
}
catch (IOException ex) {
throw new IllegalStateException("Unable to load NamespaceHandler mappings from location [" + this.handlerMappingsLocation + "]", ex);
}
}
}
}
return handlerMappings;
}
7. 返回第 2 点,实现 document 到 BeanDefinition 对象转换后,对 BeanDefinition 对象进行缓存注册
public static void registerBeanDefinition(BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
throws BeanDefinitionStoreException {
// Register bean definition under primary name.
String beanName = definitionHolder.getBeanName();
// 实现 BeanDefinition 的注册,重点看,重要水平 5
registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
// 建设别名和 id 的映射,这样就能够依据别名获取到 id (别名逻辑暂不关注)
// Register aliases for bean name, if any.
String[] aliases = definitionHolder.getAliases();
if (aliases != null) {for (String alias : aliases) {registry.registerAlias(beanName, alias);
}
}
}
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 {((AbstractBeanDefinition) beanDefinition).validate();}
catch (BeanDefinitionValidationException ex) {throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
"Validation of bean definition failed", ex);
}
}
// 先判断 BeanDefinition 是否曾经注册
BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
if (existingDefinition != null) {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 + "]");
}
}
this.beanDefinitionMap.put(beanName, beanDefinition);
}
else {if (hasBeanCreationStarted()) {// Cannot modify startup-time collection elements anymore (for stable iteration)
synchronized (this.beanDefinitionMap) {this.beanDefinitionMap.put(beanName, beanDefinition);
List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
updatedDefinitions.addAll(this.beanDefinitionNames);
updatedDefinitions.add(beanName);
this.beanDefinitionNames = updatedDefinitions;
if (this.manualSingletonNames.contains(beanName)) {Set<String> updatedSingletons = new LinkedHashSet<>(this.manualSingletonNames);
updatedSingletons.remove(beanName);
this.manualSingletonNames = updatedSingletons;
}
}
}
else {
// 把 beanDefinition 缓存到 map 中
// Still in startup registration phase
this.beanDefinitionMap.put(beanName, beanDefinition);
// 把 beanName 放到 beanDefinitionNames list 中,这个 list 着重记住,bean 实例化的时候须要用到
this.beanDefinitionNames.add(beanName);
this.manualSingletonNames.remove(beanName);
}
this.frozenBeanDefinitionNames = null;
}
if (existingDefinition != null || containsSingleton(beanName)) {
// 重置容器,外部会递归
resetBeanDefinition(beanName);
}
}
到这里默认标签的解析工作就实现了
总结:
- 默认标签次要包含 import bean alias 等,以 bean 元素为例,
- 首先解析 id、class 属性,创立 beanDefinition 对象
- 解析 bean 元素可能配置的属性,子元素等信息。例如:property 元素,constructor 元素,lookup 等元素,解析实现后,将数据封装到对应的对象上,而后设置到 beanDefinition 对象属性中,而后返回。
- 将 beanDefinition 放在到 holder 上,判断默认元素是否蕴含自定义元素(<bean class=”xx” p:username=”jack”/>),包含则进行解析,将数据设置到 beanDefinition 对象上
- 注册 beanDefinition 到 beanDefinitionMap 汇合中,注册 beanName 到 beanDefinitionNames 汇合中,注册别名 aliasMap 中
正文完