try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// 1. 包含了BeanDefinition注册过程
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// 2. 根据BeanDefinition处理Bean实例化过程
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
finishRefresh();
}
@Configuration
@Order(1)
@Import(TestAutowiredRegistar.class)
public class FirstConfig {
//1.先处理TestAutowiredRegistar的ImportBeanDefinitionRegistrar#registerBeanDefinitions
@Configuration
@Order(2)
public class SecondConfig {
@Bean
public TestRegistarDependOn testRegistarDependOn(){
return new TestRegistarDependOn();
}
}
// Process any @ComponentScan annotations
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
if (!componentScans.isEmpty() &&
!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
for (AnnotationAttributes componentScan : componentScans) {
// The config class is annotated with @ComponentScan -> perform the scan immediately
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
// Check the set of scanned definitions for any further config classes and parse recursively if needed
for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
if (bdCand == null) {
bdCand = holder.getBeanDefinition();
}
//判断扫描到的是不是配置类,是的话就进行配置处理
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
parse(bdCand.getBeanClassName(), holder.getBeanName());
}
}
}
}
的过程中的,所以假如在@Bean修饰的方法中使用到@Autowired注解依赖的bean是怎么样的场景? spring 实例化Bean过程
先了解一下实例化bean的过程是怎么样的。在finishBeanFactoryInitialization中,遍历所有的BeanDefinition信息来实例化bean。遍历的顺序调试几次后发现是按照注册BeanDefinition信息的先后顺序。所以可以有几个简单规则可以判断哪个bean会先实例化。
@Configuration
public class TestDependOnConfig {
@Autowired
ZTestConfigurationDependOn zTestConfigurationDependOn;//观察这个依赖什么时候进行初始化,断点getBean调试
@Bean
public ConfigInitBean configInitBean(){
zTestConfigurationDependOn.saySome();
return new ConfigInitBean();
}
}
@Component
public class ZTestConfigurationDependOn {
public void saySome(){
System.out.println("say some");
}
}