在 springboot 中,默认场景下不需要做@ComponentScan等组件扫描之类的配置,spring 会根据@SpringBootApplication标识的配置类来扫描其当前包及其子包下面的所有组件。
Bean 的注册流程大致分为两步:
- 注册配置类;
- 解析配置类。根据配置类扫描组件封装为
Bean并注册到Spring容器;
配置类的注册
简单来讲,配置类注册的注册是通过BeanDefinitionRegistry 的registerBeanDefinition方法来实现的。具体的实现类是DefaultListableBeanFactory
- 配置类何时被注册的;
- 被注册到哪里去了;
先看详细的配置类注册时序图:
可以看到:
- 配置类是在 springboot 启动时候先通过 BeanDefinitionLoader 中调用 register 方法注册的;
- 最终配置类的信息会存储在DefaultListableBeanFactory的beanDefinitionMap中,而这些信息可以通过
getBeanDefinitionNames方法来查询到。
配置类的解析
配置类的解析是通过后置处理器来ConfigurationClassPostProcessor完成的,这个后置处理器应该是 spring 中最为重要的类了。下面是官方描述:
BeanFactoryPostProcessorused for bootstrapping processing of@Configurationclasses.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
Beanmethods declared in@Configurationclasses have their corresponding bean definitions registered before any otherBeanFactoryPostProcessorexecutes.
ConfigurationClassPostProcessor是用来引导处理被@Configuration注解标记的配置类的,其优先级为最高优先级(priority-ordered),它是一个负责装载 bean 的后置处理器,负责为后续的后置处理器构建原材料。
下面分析配置类的解析流程: