本文主要是介绍SpringIOC源码分析(六)__IOC容器的初始化__BeanDefinition载入注册,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
一、前情提要
上一篇提到了IOC容器初始化的流程,及资源定位,本篇主要分析BeanDefinition的载入过程
二、BeanDefiniton载入解析
BeanDefinition是IOC容器对Bean的数据承载模型,IOC容器对Bean的管理和依赖注入的实现,是通过对BeanDefinition的各种操作来实现的,IOC容器通过一个HashMap来保持和维护这些BeanDefinition数据。
时序图:
核心流程:
- 创建DefaultListableBeanFactory容器
- 读XML文件解析出Document
- BeanDefinitionParserDelegate解析Document每个节点的元素,生成BeanDefinitionHolder,BeanDefinitionHolder是BeanDefinition对象的封装累,封装了BeanDefinition,Bean的名字和别名,用它来完成IOC容器注册
解析元素生成BeanDefinitionHolder,并向IOC容器注册BeanDefinition
三、BeanDefiniton注册
定义了hashMap来承载这些Bean
/** Map of bean definition objects, keyed by bean name */private final Map<String, BeanDefinition> beanDefinitionMap = new ConcurrentHashMap<>(256);
@Overridepublic 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 oldBeanDefinition;oldBeanDefinition = this.beanDefinitionMap.get(beanName);if (oldBeanDefinition != null) {if (!isAllowBeanDefinitionOverriding()) {throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,"Cannot register bean definition [" + beanDefinition + "] for bean '" + beanName +"': There is already [" + oldBeanDefinition + "] bound.");}else if (oldBeanDefinition.getRole() < beanDefinition.getRole()) {// e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTUREif (this.logger.isWarnEnabled()) {this.logger.warn("Overriding user-defined bean definition for bean '" + beanName +"' with a framework-generated bean definition: replacing [" +oldBeanDefinition + "] with [" + beanDefinition + "]");}}else if (!beanDefinition.equals(oldBeanDefinition)) {if (this.logger.isInfoEnabled()) {this.logger.info("Overriding bean definition for bean '" + beanName +"' with a different definition: replacing [" + oldBeanDefinition +"] with [" + beanDefinition + "]");}}else {if (this.logger.isDebugEnabled()) {this.logger.debug("Overriding bean definition for bean '" + beanName +"' with an equivalent definition: replacing [" + oldBeanDefinition +"] with [" + beanDefinition + "]");}}this.beanDefinitionMap.put(beanName, beanDefinition);}if (oldBeanDefinition != null || containsSingleton(beanName)) {resetBeanDefinition(beanName);}}
这篇关于SpringIOC源码分析(六)__IOC容器的初始化__BeanDefinition载入注册的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!