Springboot 中的 Bean 注册流程

1,702 阅读1分钟

在 springboot 中,默认场景下不需要做@ComponentScan等组件扫描之类的配置,spring 会根据@SpringBootApplication标识的配置类来扫描其当前包及其子包下面的所有组件。

Bean 的注册流程大致分为两步:

  1. 注册配置类;
  2. 解析配置类。根据配置类扫描组件封装为 Bean并注册到 Spring 容器;

配置类的注册

简单来讲,配置类注册的注册是通过BeanDefinitionRegistryregisterBeanDefinition方法来实现的。具体的实现类是DefaultListableBeanFactory

这里面有两个问题:

  1. 配置类何时被注册的;
  2. 被注册到哪里去了;

先看详细的配置类注册时序图:

可以看到:

  1. 配置类是在 springboot 启动时候先通过 BeanDefinitionLoader 中调用 register 方法注册的;
  2. 最终配置类的信息会存储在DefaultListableBeanFactory的beanDefinitionMap中,而这些信息可以通过getBeanDefinitionNames方法来查询到。

配置类的解析

配置类的解析是通过后置处理器来ConfigurationClassPostProcessor完成的,这个后置处理器应该是 spring 中最为重要的类了。下面是官方描述:

BeanFactoryPostProcessor used for bootstrapping processing of @Configuration classes.

Registered by default when using or. Otherwise, may be declared manually as with any other BeanFactoryPostProcessor.

This post processor is priority-ordered as it is important that any Bean methods declared in @Configuration classes have their corresponding bean definitions registered before any other BeanFactoryPostProcessor executes.

ConfigurationClassPostProcessor是用来引导处理被@Configuration注解标记的配置类的,其优先级为最高优先级(priority-ordered),它是一个负责装载 bean 的后置处理器,负责为后续的后置处理器构建原材料。

下面分析配置类的解析流程: