经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » Java相关 » Spring » 查看文章
Spring 源码阅读(二)IoC 容器初始化以及 BeanFactory 创建和 BeanDefinition 加载过程
来源:cnblogs  作者:LinweiWang  时间:2024/4/23 10:05:36  对本文有异议

相关代码提交记录:https://github.com/linweiwang/spring-framework-5.3.33

IoC 容器三种启动方式

XML

JavaSE:

  1. ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml")
  2. ApplicationContext context = new FileSystemXmlApplicationContext("C:/beans.xml")

JavaWeb

  1. 通过 web.xml 配置 ContextLoaderListener,指定 Spring 配置文件。

XML+注解

因为有 XML ,所以和纯 XML 启动方式一样

注解

JavaSE

  1. ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class)

JavaWeb

  1. 通过 web.xml 配置 ContextLoaderListener,指定 Spring 配置文件。

BeanFactory 是 Spring 框架中 IoC 容器的顶层接?,它只是?来定义?些基础功能,定义?些基础规范,? ApplicationContext 是它的?个?接?,所以 ApplicationContext 是具备 BeanFactory 提供的全部功能力的。
通常,我们称 BeanFactory 为 SpringIOC 的基础容器,ApplicationContext 是容器的?级接?,?
BeanFactory 要拥有更多的功能,?如说国际化?持和资源访问(XML、Java 配置类)等等。

image

下面以纯 XML 依赖原有 spring-research 来跟踪源码。

IoC 容器初始化主体流程

分析 new ClassPathXmlApplicationContext("spring-config.xml");

ClassPathXmlApplicationContext.java

  1. // 创建 ClassPathXmlApplicationContext,加载 XML 中的定义信息,并且自动 refresh 容器(Context)
  2. public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
  3. // 调用重载方法
  4. this(new String[] {configLocation}, true, null);
  5. }
  6. public ClassPathXmlApplicationContext(
  7. String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
  8. throws BeansException {
  9. // 初始化父类
  10. super(parent);
  11. // 设置配置文件
  12. setConfigLocations(configLocations);
  13. // refresh context
  14. if (refresh) {
  15. refresh();
  16. }
  17. }

进入 refresh() 方法,在父类 AbstractApplicationContext 中

  1. @Override
  2. public void refresh() throws BeansException, IllegalStateException {
  3. // 对象锁
  4. synchronized (this.startupShutdownMonitor) {
  5. StartupStep contextRefresh = this.applicationStartup.start("spring.context.refresh");
  6. // 刷新前的预处理
  7. // Prepare this context for refreshing.
  8. prepareRefresh();
  9. // 获取 BeanFactory: 默认实现是 DefaultListableBeanFactory
  10. // 加载 BeanDefinition 并注册到 BeanDefinitionRegistry
  11. // Tell the subclass to refresh the internal bean factory.
  12. ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
  13. // BeanFactory 预准备工作
  14. // Prepare the bean factory for use in this context.
  15. prepareBeanFactory(beanFactory);
  16. try {
  17. // BeanFactory 准备工作完成后的后置处理,留给子类实现
  18. // Allows post-processing of the bean factory in context subclasses.
  19. postProcessBeanFactory(beanFactory);
  20. StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
  21. // 实例化实现了 BeanFactoryPostProcessor 接口的 Bean,并调用该接口方法
  22. // Invoke factory processors registered as beans in the context.
  23. invokeBeanFactoryPostProcessors(beanFactory);
  24. // 注册 BeanPostProcessor (Bean 的后置处理器),在创建 Bean 的前后执行
  25. // Register bean processors that intercept bean creation.
  26. registerBeanPostProcessors(beanFactory);
  27. beanPostProcess.end();
  28. // 初始化 MessageSource 组件:国际化、消息绑定、消息解析等
  29. // Initialize message source for this context.
  30. initMessageSource();
  31. // 初始化事件派发器
  32. // Initialize event multicaster for this context.
  33. initApplicationEventMulticaster();
  34. // 初始化其他特殊的 Bean,在容器刷新的时候子类自定义实现:如创建 Tomcat、Jetty 等 Web 服务器
  35. // Initialize other special beans in specific context subclasses.
  36. onRefresh();
  37. // 注册应用监听器(即实现了 ApplicationListener 接口的 Bean)
  38. // Check for listener beans and register them.
  39. registerListeners();
  40. // 初始化创建非懒加载的单例 Bean、填充属性、调用初始化方法( afterPropertiesSet,init-method 等)、调用 BeanPostProcessor 后置处理器
  41. // Instantiate all remaining (non-lazy-init) singletons.
  42. finishBeanFactoryInitialization(beanFactory);
  43. // 完成 context 刷新,调用 LifecycleProcessor 的 onRefresh 方法并发布 ContextRefreshedEvent
  44. // Last step: publish corresponding event.
  45. finishRefresh();
  46. }
  47. catch (BeansException ex) {
  48. if (logger.isWarnEnabled()) {
  49. logger.warn("Exception encountered during context initialization - " +
  50. "cancelling refresh attempt: " + ex);
  51. }
  52. // Destroy already created singletons to avoid dangling resources.
  53. destroyBeans();
  54. // Reset 'active' flag.
  55. cancelRefresh(ex);
  56. // Propagate exception to caller.
  57. throw ex;
  58. }
  59. finally {
  60. // Reset common introspection caches in Spring's core, since we
  61. // might not ever need metadata for singleton beans anymore...
  62. resetCommonCaches();
  63. contextRefresh.end();
  64. }
  65. }
  66. }

整体流程如下:

1 刷新前的预处理: prepareRefresh();
 主要是一些准备工作设置其启动日期和活动标志以及执行一些属性的初始化。
 
 2 初始化 BeanFactory: obtainFreshBeanFactory();

  • 如果有旧的 BeanFactory 就删除并创建新的 BeanFactory
  • 解析所有的 Spring 配置文件,将配置文件中定义的 bean 封装成 BeanDefinition,加载到BeanFactory 中(这里只注册,不会进行 Bean 的实例化)

3 BeanFactory 预准备工作:prepareBeanFactory(beanFactory);
配置 BeanFactory 的标准上下文特征,例如上下文的 ClassLoader、后置处理器等。

4 BeanFactory 准备工作完成后的后置处理,留给子类实现:postProcessBeanFactory(beanFactory);
空方法,如果子类需要,自己去实现

5 调用 Bean 工厂后置处理器:invokeBeanFactoryPostProcessors(beanFactory);

实例化和调用所有BeanFactoryPostProcessor,完成类的扫描、解析和注册。
BeanFactoryPostProcessor 接口是 Spring 初始化 BeanFactory 时对外暴露的扩展点,Spring IoC 容器允许 BeanFactoryPostProcessor 在容器实例化任何 bean 之前读取 bean 的定义,并可以修改它。

6 注册 BeanPostProcesso:registerBeanPostProcessors(beanFactory);
所有实现了 BeanPostProcessor 接口的类注册到 BeanFactory 中。

7 初始化 MessageSource 组件:initMessageSource();
初始化MessageSource组件(做国际化功能;消息绑定,消息解析)

8 初始化事件派发器:initApplicationEventMulticaster();
初始化应用的事件派发/广播器 ApplicationEventMulticaster。

9 初始化其他特殊的 Bean:onRefresh();
空方法,模板设计模式;子类重写该方法并在容器刷新的时候自定义逻辑。
例:SpringBoot 在 onRefresh() 完成内置 Tomcat 的创建及启动

10 注册应用监听器:registerListeners();
向事件分发器注册硬编码设置的 ApplicationListener,向事件分发器注册一个 IoC 中的事件监听器(并不实例化)

11 初始化创建非懒加载的单例 Bean:finishBeanFactoryInitialization(beanFactory);
初始化创建非懒加载的单例 Bean、填充属性、调用初始化方法( afterPropertiesSet,init-method 等)、调用 BeanPostProcessor 后置处理器,是整个 Spring IoC 核心中的核心。

12 完成 context 刷新:finishRefresh();
完成 context 刷新,调用 LifecycleProcessor 的 onRefresh 方法并发布 ContextRefreshedEvent

获取 BeanFactory 子流程

ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

AbstractApplicationContext.java

  1. protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
  2. // 对 BeanFactory 进行刷新操作,默认实现 AbstractRefreshableApplicationContext#refreshBeanFactory
  3. refreshBeanFactory();
  4. // 返回上一步 beanFactory,默认实现 AbstractRefreshableApplicationContext#getBeanFactory
  5. return getBeanFactory();
  6. }

AbstractRefreshableApplicationContext

  1. @Override
  2. protected final void refreshBeanFactory() throws BeansException {
  3. // 判断是否已有 BeanFactory
  4. if (hasBeanFactory()) {
  5. // 销毁 Bean
  6. destroyBeans();
  7. // 关闭 BeanFactory
  8. closeBeanFactory();
  9. }
  10. try {
  11. // 实例化 DefaultListableBeanFactory
  12. DefaultListableBeanFactory beanFactory = createBeanFactory();
  13. // 设置序列化 ID
  14. beanFactory.setSerializationId(getId());
  15. // 自定义 BeanFactory 的一些属性:allowBeanDefinitionOverriding、allowCircularReferences
  16. // allowBeanDefinitionOverriding 是否允许覆盖
  17. // allowCircularReferences 是否允许循环依赖
  18. customizeBeanFactory(beanFactory);
  19. // 加载应用中的 BeanFactory
  20. loadBeanDefinitions(beanFactory);
  21. // 赋值给当前 beanFactory 属性
  22. this.beanFactory = beanFactory;
  23. }
  24. catch (IOException ex) {
  25. throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
  26. }
  27. }
  28. @Override
  29. public final ConfigurableListableBeanFactory getBeanFactory() {
  30. DefaultListableBeanFactory beanFactory = this.beanFactory;
  31. if (beanFactory == null) {
  32. throw new IllegalStateException("BeanFactory not initialized or already closed - " +
  33. "call 'refresh' before accessing beans via the ApplicationContext");
  34. }
  35. return beanFactory;
  36. }

image

BeanDefinition 加载解析及注册子流程

继续分析 AbstractRefreshableApplicationContext#refreshBeanFactory 中的 loadBeanDefinitions 的实现方法在 AbstractXmlApplicationContext#loadBeanDefinitions 中(若是注解在 AnnotationConfigWebApplicationContext)

AbstractXmlApplicationContext

  1. @Override
  2. protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException {
  3. // 给指定的 BeanFactory 创建一个 XmlBeanDefinitionReader 进行读取和解析 XML
  4. // Create a new XmlBeanDefinitionReader for the given BeanFactory.
  5. XmlBeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(beanFactory);
  6. // 给 XmlBeanDefinitionReader 设置上下文信息
  7. // Configure the bean definition reader with this context's
  8. // resource loading environment.
  9. beanDefinitionReader.setEnvironment(getEnvironment());
  10. beanDefinitionReader.setResourceLoader(this);
  11. beanDefinitionReader.setEntityResolver(new ResourceEntityResolver(this));
  12. // 提供给子类上西安的模板方法:自定义初始化策略
  13. // Allow a subclass to provide custom initialization of the reader,
  14. // then proceed with actually loading the bean definitions.
  15. initBeanDefinitionReader(beanDefinitionReader);
  16. // 真正的去加载 BeanDefinitions
  17. loadBeanDefinitions(beanDefinitionReader);
  18. }
  19. protected void loadBeanDefinitions(XmlBeanDefinitionReader reader) throws BeansException, IOException {
  20. // 从 Resource 资源对象加载 BeanDefinitions
  21. Resource[] configResources = getConfigResources();
  22. if (configResources != null) {
  23. reader.loadBeanDefinitions(configResources);
  24. }
  25. // 从 XML 配置文件加载 BeanDefinition 对象
  26. String[] configLocations = getConfigLocations();
  27. if (configLocations != null) {
  28. reader.loadBeanDefinitions(configLocations);
  29. }
  30. }

reader.loadBeanDefinitions(configLocations); 中调用了 AbstractBeanDefinitionReader#loadBeanDefinitions

  1. @Override
  2. public int loadBeanDefinitions(String... locations) throws BeanDefinitionStoreException {
  3. Assert.notNull(locations, "Location array must not be null");
  4. int count = 0;
  5. // 如果有多个配置文件,循环读取加载,并统计数量
  6. for (String location : locations) {
  7. count += loadBeanDefinitions(location);
  8. }
  9. return count;
  10. }
  11. @Override
  12. public int loadBeanDefinitions(String location) throws BeanDefinitionStoreException {
  13. return loadBeanDefinitions(location, null);
  14. }
  15. public int loadBeanDefinitions(String location, @Nullable Set<Resource> actualResources) throws BeanDefinitionStoreException {
  16. // 获取上下文的 ResourceLoader (资源加载器)
  17. ResourceLoader resourceLoader = getResourceLoader();
  18. if (resourceLoader == null) {
  19. throw new BeanDefinitionStoreException(
  20. "Cannot load bean definitions from location [" + location + "]: no ResourceLoader available");
  21. }
  22. // 判断资源加载器是否为 ResourcePatternResolver 类型
  23. if (resourceLoader instanceof ResourcePatternResolver) {
  24. // Resource pattern matching available.
  25. try {
  26. // 统一加载转换为 Resource 对象
  27. Resource[] resources = ((ResourcePatternResolver) resourceLoader).getResources(location);
  28. // 通过 Resource 对象加载 BeanDefinitions
  29. int count = loadBeanDefinitions(resources);
  30. if (actualResources != null) {
  31. Collections.addAll(actualResources, resources);
  32. }
  33. if (logger.isTraceEnabled()) {
  34. logger.trace("Loaded " + count + " bean definitions from location pattern [" + location + "]");
  35. }
  36. return count;
  37. }
  38. catch (IOException ex) {
  39. throw new BeanDefinitionStoreException(
  40. "Could not resolve bean definition resource pattern [" + location + "]", ex);
  41. }
  42. }
  43. else {
  44. // 否则以绝对路径转换为 Resource 对象
  45. // Can only load single resources by absolute URL.
  46. Resource resource = resourceLoader.getResource(location);
  47. int count = loadBeanDefinitions(resource);
  48. if (actualResources != null) {
  49. actualResources.add(resource);
  50. }
  51. if (logger.isTraceEnabled()) {
  52. logger.trace("Loaded " + count + " bean definitions from location [" + location + "]");
  53. }
  54. return count;
  55. }
  56. }
  57. @Override
  58. public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
  59. Assert.notNull(resources, "Resource array must not be null");
  60. int count = 0;
  61. for (Resource resource : resources) {
  62. count += loadBeanDefinitions(resource);
  63. }
  64. return count;
  65. }
  66. @Override
  67. public int loadBeanDefinitions(Resource... resources) throws BeanDefinitionStoreException {
  68. Assert.notNull(resources, "Resource array must not be null");
  69. int count = 0;
  70. for (Resource resource : resources) {
  71. // 加载
  72. count += loadBeanDefinitions(resource);
  73. }
  74. return count;
  75. }

loadBeanDefinitions(resource); 调用了 XmlBeanDefinitionReader#loadBeanDefinitions 方法

  1. @Override
  2. public int loadBeanDefinitions(Resource resource) throws BeanDefinitionStoreException {
  3. return loadBeanDefinitions(new EncodedResource(resource));
  4. }
  5. public int loadBeanDefinitions(EncodedResource encodedResource) throws BeanDefinitionStoreException {
  6. Assert.notNull(encodedResource, "EncodedResource must not be null");
  7. if (logger.isTraceEnabled()) {
  8. logger.trace("Loading XML bean definitions from " + encodedResource);
  9. }
  10. Set<EncodedResource> currentResources = this.resourcesCurrentlyBeingLoaded.get();
  11. if (!currentResources.add(encodedResource)) {
  12. throw new BeanDefinitionStoreException(
  13. "Detected cyclic loading of " + encodedResource + " - check your import definitions!");
  14. }
  15. try (InputStream inputStream = encodedResource.getResource().getInputStream()) {
  16. // 把 XML 文件流封装为 InputSource 对象
  17. InputSource inputSource = new InputSource(inputStream);
  18. if (encodedResource.getEncoding() != null) {
  19. inputSource.setEncoding(encodedResource.getEncoding());
  20. }
  21. // 执行加载逻辑
  22. return doLoadBeanDefinitions(inputSource, encodedResource.getResource());
  23. }
  24. catch (IOException ex) {
  25. throw new BeanDefinitionStoreException(
  26. "IOException parsing XML document from " + encodedResource.getResource(), ex);
  27. }
  28. finally {
  29. currentResources.remove(encodedResource);
  30. if (currentResources.isEmpty()) {
  31. this.resourcesCurrentlyBeingLoaded.remove();
  32. }
  33. }
  34. }
  35. protected int doLoadBeanDefinitions(InputSource inputSource, Resource resource)
  36. throws BeanDefinitionStoreException {
  37. try {
  38. // 读取 XML 信息,将 XML 中信息保存到 Document 对象中
  39. Document doc = doLoadDocument(inputSource, resource);
  40. // 再解析 Document 对象,封装为 BeanDefinition 对象进行注册
  41. int count = registerBeanDefinitions(doc, resource);
  42. if (logger.isDebugEnabled()) {
  43. logger.debug("Loaded " + count + " bean definitions from " + resource);
  44. }
  45. return count;
  46. }
  47. catch (BeanDefinitionStoreException ex) {
  48. throw ex;
  49. }
  50. catch (SAXParseException ex) {
  51. throw new XmlBeanDefinitionStoreException(resource.getDescription(),
  52. "Line " + ex.getLineNumber() + " in XML document from " + resource + " is invalid", ex);
  53. }
  54. catch (SAXException ex) {
  55. throw new XmlBeanDefinitionStoreException(resource.getDescription(),
  56. "XML document from " + resource + " is invalid", ex);
  57. }
  58. catch (ParserConfigurationException ex) {
  59. throw new BeanDefinitionStoreException(resource.getDescription(),
  60. "Parser configuration exception parsing XML from " + resource, ex);
  61. }
  62. catch (IOException ex) {
  63. throw new BeanDefinitionStoreException(resource.getDescription(),
  64. "IOException parsing XML document from " + resource, ex);
  65. }
  66. catch (Throwable ex) {
  67. throw new BeanDefinitionStoreException(resource.getDescription(),
  68. "Unexpected exception parsing XML document from " + resource, ex);
  69. }
  70. }
  71. public int registerBeanDefinitions(Document doc, Resource resource) throws BeanDefinitionStoreException {
  72. BeanDefinitionDocumentReader documentReader = createBeanDefinitionDocumentReader();
  73. // 获取已有 BeanDefinition 的数量
  74. int countBefore = getRegistry().getBeanDefinitionCount();
  75. // 注册 BeanDefinition
  76. documentReader.registerBeanDefinitions(doc, createReaderContext(resource));
  77. // 计算出新注册的 BeanDefinition 数量
  78. return getRegistry().getBeanDefinitionCount() - countBefore;
  79. }

documentReader.registerBeanDefinitions(doc, createReaderContext(resource)); 会进入 DefaultBeanDefinitionDocumentReader#registerBeanDefinitions

  1. @Override
  2. public void registerBeanDefinitions(Document doc, XmlReaderContext readerContext) {
  3. this.readerContext = readerContext;
  4. doRegisterBeanDefinitions(doc.getDocumentElement());
  5. }
  6. protected void doRegisterBeanDefinitions(Element root) {
  7. // Any nested <beans> elements will cause recursion in this method. In
  8. // order to propagate and preserve <beans> default-* attributes correctly,
  9. // keep track of the current (parent) delegate, which may be null. Create
  10. // the new (child) delegate with a reference to the parent for fallback purposes,
  11. // then ultimately reset this.delegate back to its original (parent) reference.
  12. // this behavior emulates a stack of delegates without actually necessitating one.
  13. BeanDefinitionParserDelegate parent = this.delegate;
  14. this.delegate = createDelegate(getReaderContext(), root, parent);
  15. if (this.delegate.isDefaultNamespace(root)) {
  16. String profileSpec = root.getAttribute(PROFILE_ATTRIBUTE);
  17. if (StringUtils.hasText(profileSpec)) {
  18. String[] specifiedProfiles = StringUtils.tokenizeToStringArray(
  19. profileSpec, BeanDefinitionParserDelegate.MULTI_VALUE_ATTRIBUTE_DELIMITERS);
  20. // We cannot use Profiles.of(...) since profile expressions are not supported
  21. // in XML config. See SPR-12458 for details.
  22. if (!getReaderContext().getEnvironment().acceptsProfiles(specifiedProfiles)) {
  23. if (logger.isDebugEnabled()) {
  24. logger.debug("Skipped XML bean definition file due to specified profiles [" + profileSpec +
  25. "] not matching: " + getReaderContext().getResource());
  26. }
  27. return;
  28. }
  29. }
  30. }
  31. preProcessXml(root);
  32. // 真正解析 XML
  33. parseBeanDefinitions(root, this.delegate);
  34. postProcessXml(root);
  35. this.delegate = parent;
  36. }
  37. protected void parseBeanDefinitions(Element root, BeanDefinitionParserDelegate delegate) {
  38. if (delegate.isDefaultNamespace(root)) {
  39. NodeList nl = root.getChildNodes();
  40. for (int i = 0; i < nl.getLength(); i++) {
  41. Node node = nl.item(i);
  42. if (node instanceof Element) {
  43. Element ele = (Element) node;
  44. if (delegate.isDefaultNamespace(ele)) {
  45. // 解析默认标签元素:"import", "alias", "bean"
  46. parseDefaultElement(ele, delegate);
  47. }
  48. else {
  49. // 解析自定义标签
  50. delegate.parseCustomElement(ele);
  51. }
  52. }
  53. }
  54. }
  55. else {
  56. // 解析自定义标签
  57. delegate.parseCustomElement(root);
  58. }
  59. }
  60. private void parseDefaultElement(Element ele, BeanDefinitionParserDelegate delegate) {
  61. // import 标签
  62. if (delegate.nodeNameEquals(ele, IMPORT_ELEMENT)) {
  63. importBeanDefinitionResource(ele);
  64. }
  65. // alias 标签
  66. else if (delegate.nodeNameEquals(ele, ALIAS_ELEMENT)) {
  67. processAliasRegistration(ele);
  68. }
  69. // bean 标签:着重分析
  70. else if (delegate.nodeNameEquals(ele, BEAN_ELEMENT)) {
  71. processBeanDefinition(ele, delegate);
  72. }
  73. // 嵌套 bean 标签
  74. else if (delegate.nodeNameEquals(ele, NESTED_BEANS_ELEMENT)) {
  75. // recurse
  76. doRegisterBeanDefinitions(ele);
  77. }
  78. }
  79. protected void processBeanDefinition(Element ele, BeanDefinitionParserDelegate delegate) {
  80. // 解析 bean 标签为 BeanDefinitionHolder 里面持有 BeanDefinition
  81. BeanDefinitionHolder bdHolder = delegate.parseBeanDefinitionElement(ele);
  82. if (bdHolder != null) {
  83. // 若有必要装饰 bdHolder (bean 标签内有自定义标签的情况下)
  84. bdHolder = delegate.decorateBeanDefinitionIfRequired(ele, bdHolder);
  85. try {
  86. // 完成 BeanDefinition 的注册
  87. // Register the final decorated instance.
  88. BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry());
  89. }
  90. catch (BeanDefinitionStoreException ex) {
  91. getReaderContext().error("Failed to register bean definition with name '" +
  92. bdHolder.getBeanName() + "'", ele, ex);
  93. }
  94. // Send registration event.
  95. getReaderContext().fireComponentRegistered(new BeanComponentDefinition(bdHolder));
  96. }
  97. }

BeanDefinitionReaderUtils.registerBeanDefinition(bdHolder, getReaderContext().getRegistry()); 调用了 BeanDefinitionReaderUtils#registerBeanDefinition

  1. public static void registerBeanDefinition(
  2. BeanDefinitionHolder definitionHolder, BeanDefinitionRegistry registry)
  3. throws BeanDefinitionStoreException {
  4. // 注册
  5. // Register bean definition under primary name.
  6. String beanName = definitionHolder.getBeanName();
  7. registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition());
  8. // Register aliases for bean name, if any.
  9. String[] aliases = definitionHolder.getAliases();
  10. if (aliases != null) {
  11. for (String alias : aliases) {
  12. registry.registerAlias(beanName, alias);
  13. }
  14. }
  15. }

registry.registerBeanDefinition(beanName, definitionHolder.getBeanDefinition()); 调用了 DefaultListableBeanFactory#registerBeanDefinition

  1. @Override
  2. public void registerBeanDefinition(String beanName, BeanDefinition beanDefinition)
  3. throws BeanDefinitionStoreException {
  4. Assert.hasText(beanName, "Bean name must not be empty");
  5. Assert.notNull(beanDefinition, "BeanDefinition must not be null");
  6. if (beanDefinition instanceof AbstractBeanDefinition) {
  7. try {
  8. ((AbstractBeanDefinition) beanDefinition).validate();
  9. }
  10. catch (BeanDefinitionValidationException ex) {
  11. throw new BeanDefinitionStoreException(beanDefinition.getResourceDescription(), beanName,
  12. "Validation of bean definition failed", ex);
  13. }
  14. }
  15. BeanDefinition existingDefinition = this.beanDefinitionMap.get(beanName);
  16. if (existingDefinition != null) {
  17. if (!isAllowBeanDefinitionOverriding()) {
  18. throw new BeanDefinitionOverrideException(beanName, beanDefinition, existingDefinition);
  19. }
  20. else if (existingDefinition.getRole() < beanDefinition.getRole()) {
  21. // e.g. was ROLE_APPLICATION, now overriding with ROLE_SUPPORT or ROLE_INFRASTRUCTURE
  22. if (logger.isInfoEnabled()) {
  23. logger.info("Overriding user-defined bean definition for bean '" + beanName +
  24. "' with a framework-generated bean definition: replacing [" +
  25. existingDefinition + "] with [" + beanDefinition + "]");
  26. }
  27. }
  28. else if (!beanDefinition.equals(existingDefinition)) {
  29. if (logger.isDebugEnabled()) {
  30. logger.debug("Overriding bean definition for bean '" + beanName +
  31. "' with a different definition: replacing [" + existingDefinition +
  32. "] with [" + beanDefinition + "]");
  33. }
  34. }
  35. else {
  36. if (logger.isTraceEnabled()) {
  37. logger.trace("Overriding bean definition for bean '" + beanName +
  38. "' with an equivalent definition: replacing [" + existingDefinition +
  39. "] with [" + beanDefinition + "]");
  40. }
  41. }
  42. this.beanDefinitionMap.put(beanName, beanDefinition);
  43. }
  44. else {
  45. // 注册逻辑
  46. if (hasBeanCreationStarted()) {
  47. // Cannot modify startup-time collection elements anymore (for stable iteration)
  48. synchronized (this.beanDefinitionMap) {
  49. this.beanDefinitionMap.put(beanName, beanDefinition);
  50. List<String> updatedDefinitions = new ArrayList<>(this.beanDefinitionNames.size() + 1);
  51. updatedDefinitions.addAll(this.beanDefinitionNames);
  52. updatedDefinitions.add(beanName);
  53. this.beanDefinitionNames = updatedDefinitions;
  54. removeManualSingletonName(beanName);
  55. }
  56. }
  57. else {
  58. // Still in startup registration phase
  59. this.beanDefinitionMap.put(beanName, beanDefinition);
  60. this.beanDefinitionNames.add(beanName);
  61. removeManualSingletonName(beanName);
  62. }
  63. this.frozenBeanDefinitionNames = null;
  64. }
  65. if (existingDefinition != null || containsSingleton(beanName)) {
  66. resetBeanDefinition(beanName);
  67. }
  68. else if (isConfigurationFrozen()) {
  69. clearByTypeCache();
  70. }
  71. }

整体调用链如下

  1. AbstractRefreshableApplicationContext#refreshBeanFactory
  2. AbstractXmlApplicationContext#loadBeanDefinitions
  3. AbstractBeanDefinitionReader#loadBeanDefinitions // 加载 BeanDefinition
  4. XmlBeanDefinitionReader#loadBeanDefinitions
  5. XmlBeanDefinitionReader#doLoadBeanDefinitions // 读取 XML 为 Document
  6. XmlBeanDefinitionReader#registerBeanDefinitions // 真正开始注册
  7. DefaultBeanDefinitionDocumentReader#registerBeanDefinitions
  8. DefaultBeanDefinitionDocumentReader#doRegisterBeanDefinitions
  9. DefaultBeanDefinitionDocumentReader#parseBeanDefinitions
  10. DefaultBeanDefinitionDocumentReader#parseDefaultElement
  11. DefaultBeanDefinitionDocumentReader#processBeanDefinition
  12. BeanDefinitionReaderUtils#registerBeanDefinition
  13. DefaultListableBeanFactory#registerBeanDefinition

image

原文链接:https://www.cnblogs.com/linweiwang/p/18151805

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号