前言
本文使用的SpringBoot环境,默认使用的是AnnotationConfigApplicationContext上下文对象
一般我们使用@Bean一般都写在@Configuration注释的类下,Spring会帮我们将@Bean注释的方法返回的对象添加进容器中
如:
@Configuration
public class MyMapperConfig {
@Bean
public Car car(){
return new Car();
}
}
Tip
如果看过Spring源码或者已经了解扫描注解的过程可以直接看源码,下面我指出了几个位置
封装BeanMethod位置
ConfigurationClassParser 的 doProcessConfigurationClass() 方法。此方法将类的方法封装为BeanMethod
BeanMethod转换为BeanDefinition
ConfigurationClassBeanDefinitionReader 的 loadBeanDefinitionsForBeanMethod() 方法
如何搜索到@Bean注释的方法?
Spring源码一般都会从refresh方法开始调试
在AbstractApplicationContext 的refresh()方法中会执行如下代码,注册BeanDefinition
// Invoke factory processors registered as beans in the context.
// 调用在上下文中注册为 bean 的工厂处理器
invokeBeanFactoryPostProcessors(beanFactory);
由于context默认注入了ConfigurationClassPostProcessor 类,会进入processConfigBeanDefinitions()方法,该方法中会使用ConfigurationClassParser类的parse方法进行解析
// Parse each @Configuration class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
// 解析
parser.parse(candidates);
parser.validate();
Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.