spring源码版本 spring-framework-5.3.10
源码思维导图
https://www.processon.com/v/64b0f88ab856374c5c180238
解析配置类的代码路径
AnnotationConfigApplicationContext(Class) -> refresh() -> invokeBeanFactoryPostProcessors() -> invokeBeanFactoryPostProcessors(beanFactory,beanFactoryPostProcessors)
ConfigurationClassPostProcessor.postProcessBeanDefinitionRegistry()代码块解析
再如下 代码块 1 中当执行到invokeBeanDefinitionRegistryPostProcessors()传入的参数ConfigurationClassPostProcessor这个Bean的时候,会在调用它的postProcessBeanDefinitionRegistry()方法中去解析配置类,方法实现 具体如下代码块2 所示
// 代码块 1
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) { // BeanFactoryPostProcessor、BeanDefinitionRegistryPostProcessor
// ......代码略
// 执行扫描出来的BeanDefinitionRegistryPostProcessor
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
// 升序排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
currentRegistryProcessors.clear();
// ......代码略
}
// 代码块 2
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
if (this.registriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
}
if (this.factoriesPostProcessed.contains(registryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + registry);
}
this.registriesPostProcessed.add(registryId);
// 解析配置类
processConfigBeanDefinitions(registry);
}
解析配置类processConfigBeanDefinitions的方法代码分析
思路:
- 判断哪些是配置类- checkConfigurationClassCandidate()
- 查看是否有注解-@Configuration
存在@Configuration,并且proxyBeanMethods不为false(为true或为null)时,就是Full配置类
存在@Configuration,并且proxyBeanMethods为false时,是lite配置类 - 只要存在@Component、@ComponentScan、@Import、@ImportResource四个中的一个,就是lite配置类
- 只要存在@Bean注解了的方法,就是lite配置类
- 查看是否有注解-@Configuration
- 解析配置类,将解析得到的BeanDefinition注册到容器中