我们在SpringFramework源码分析(2):IoC容器AnnotationConfigApplicationContext的创建中分析了AnnotationConfigApplicationContext初始化的代码。AnnotationConfigApplicationContext初始化的过程中,在AbstractApplicationContext#refresh()方法里,有一行代码invokeBeanFactoryPostProcessors(beanFactory),这行代码的主要执行用户自定义和Spring提供的BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,完成了Spring对用户提供的基于注解的配置类的扫描,将配置类中提供的类转化成了BeanDefinition并注册到BeanFactory的beanDefinitionMap中。我们将在本篇文章中,对invokeBeanFactoryPostProcessors(beanFactory)进行较为详尽的解读。
1 BeanFactoryPostProcessor的执行
首先,invokeBeanFactoryPostProcessors中主要就是调用了下面这行代码。需要注意的是,getBeanFactoryPostProcessors()获取到的是用户通过AnnotationConfigApplicationContext#addBeanFactoryPostProcessor方法手动添加的BeanFactoryPostProcessor集合,并不是Spring内置的BeanFactoryPostProcessor。
/**
* Instantiate and invoke all registered BeanFactoryPostProcessor beans,
* respecting explicit order if given.
* <p>Must be called before singleton instantiation.
*/
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
/*
* getBeanFactoryPostProcessors()获取的是当前类的属性this.beanFactoryPostProcessors,而当前类只有addBeanFactoryPostProcessor方法向beanFactoryPostProcessors增加了BeanFactoryPostProcessor,
* 所以getBeanFactoryPostProcessors()的结果只能是用户代码显示地调用applicationContext.addBeanFactoryPostProcessor(new MyBeanFactoryPostProcessor())添加的BeanFactoryPostProcessor;
* */
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
接下来,我们看下PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors方法。这个方法看起来挺长的,并且里面好像还写了些重复的代码。我们在看代码前,先捋顺一下整个方法的思路。
- 从invokeBeanFactoryPostProcessors这个方法名看出,该方法是要执行BeanFactoryPostProcessor。
- BeanFactoryPostProcessor作为Spring的一个扩展点,是允许用户自行添加的,该方法的第二个参数就是用户添加的BeanPostProcessor接口的实现类。因此,这个方法会执行Spring内置的BeanPostProcessor和用户提供的BeanPostProcessor。
- BeanDefinitionRegistryPostProcessor接口是BeanFactoryPostProcessor接口的子接口。BeanDefinitionRegistryPostProcessor提供postProcessBeanDefinitionRegistry方法,BeanFactoryPostProcessor提供提供postProcessBeanFactory方法。
结合上面的三点,该方法会执行用户提供的以及Spring内置的BeanDefinitionRegistryPostProcessor接口实现类的postProcessBeanDefinitionRegistry方法以及BeanFactoryPostProcessor接口实现类的postProcessBeanFactory方法。具体的执行逻辑,可以看下方法注释。
/**
* 该方法分别处理了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor
* 整体执行逻辑,先执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法,
* 再执行BeanFactoryPostProcessor的postProcessBeanFactory方法。
*
* 执行BeanDefinitionRegistryPostProcessor的postProcessBeanDefinitionRegistry方法的顺序:
* 先执行用户自定义的BeanDefinitionRegistryPostProcessor
* 然后执行实现了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
* 然后执行实现了Ordered接口的BeanDefinitionRegistryPostProcessor
* 然后执行其他BeanDefinitionRegistryPostProcessors
* 注意:下面这行代码执行了三遍,这是因为在调用invokeBeanDefinitionRegistryPostProcessors时,可能会向BeanFactory中注册新的BeanDefinitionRegistryPostProcessor
* postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
*
* 执行BeanFactoryPostProcessor的postProcessBeanFactory方法的顺序:
* 先执行实现了BeanDefinitionRegistryPostProcessor接口的子类的postProcessBeanFactory方法
* 再执行实现了BeanFactoryPostProcessor接口的子类的postProcessBeanFactory方法
*
* @param beanFactory beanFactory
* @param beanFactoryPostProcessors 用户手动调用applicationContext.addBeanFactoryPostProcessor()添加的BeanFactoryPostProcessor的集合
* */
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();
// 这里传入的beanFactory是DefaultListableBeanFactory,实现了BeanDefinitionRegistry接口
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 这里Spring将BeanPostProcessor接口分成了两类,分别是BeanFactoryPostProcessor和BeanDefinitionRegistryPostProcessor
// 目的在于分别处理两类接口的实现类
// 实现了BeanFactoryPostProcessor接口的集合
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// 实现了BeanDefinitionRegistryPostProcessor接口的集合
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 处理用户手动添加的自定义的BeanFactoryPostProcessor集合
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 看用户是否手动添加了BeanDefinitionRegistryPostProcessor
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
// 如果用户手动添加了自定义的BeanDefinitionRegistryPostProcessor,则先执行postProcessBeanDefinitionRegistry方法
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
else {
regularPostProcessors.add(postProcessor);
}
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// currentRegistryProcessors里面放的是Spring自己的实现了BeanDefinitionRegistryPostProcessor接口的对象
// 其实目前Spring中只有ConfigurationClassPostProcessor实现了BeanDefinitionRegistryPostProcessor接口
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// ConfigurationClassPostProcessor实现了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);
// 整个方法中,这句最关键。执行了ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 注意,下面这句代码又调用了一遍,主要是在上面的invokeBeanDefinitionRegistryPostProcessors方法中,有可能会向BeanFactory中添加新的BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
boolean reiterate = true;
while (reiterate) {
reiterate = false;
// 注意,下面这句代码又调用了一遍,主要是在上面的invokeBeanDefinitionRegistryPostProcessors方法中,有可能会向BeanFactory中添加新的BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (!processedBeans.contains(ppName)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 执行BeanBeanDefinitionRegistry接口实现类的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
// 执行BeanFactoryPostProcessor接口实现类的postProcessBeanFactory方法
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
for (String postProcessorName : nonOrderedPostProcessorNames) {
nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
// Clear cached merged bean definitions since the post-processors might have
// modified the original metadata, e.g. replacing placeholders in values...
beanFactory.clearMetadataCache();
}
如果用户没有向Spring容器中添加BeanPostProcessor的实现,那么其实上面的代码实际上只会执行ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法以及postProcessBeanFactory方法。
下面让我们来一起看下ConfigurationClassPostProcessor这个类。
2 ConfigurationClassPostProcessor的讲解
首先看下类定义,可以看到该类实现了BeanDefinitionRegistryPostProcessor、PriorityOrdered、ResourceLoaderAware、BeanClassLoaderAware、EnvironmentAware接口。
public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
PriorityOrdered, ResourceLoaderAware, BeanClassLoaderAware, EnvironmentAware
2.1 postProcessBeanDefinitionRegistry方法
整体流程
我们首先看下ConfigurationClassPostProcessor实现的BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法,该方法解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中。
/**
* 解析标注了@Configuration注解的类,即配置类,生成额外的BeanDefinition并注册到BeanFactory中
* Derive further bean definitions from the configuration classes in the registry.
*/
@Override
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方法,该方法大体流程如下。
- 从已有的BeanDefinitionNames中,找到@Configuration注解标注的配置类,加入到configCandidates中。
- 生成一个ConfigurationClassParser,通过parse方法,对configCandidates进行解析。将解析得到的类封装成ConfigurationClass,所有的解析结果存放在ConfigurationClassParser的configurationClasses中,configurationClasses是一个Map。
- 初始化一个ConfigurationClassBeanDefinitionReader,用来将ConfigClasses转化成BeanDefinition,注册到BeanFactory中。
/**
* 处理标注了@Configuration的类
* Build and validate a configuration model based on the registry of
* {@link Configuration} classes.
* @param registry 这里的registry是DefaultListableBeanFactory
*/
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
// 从已有的BeanDefinitionNames中,找到@Configuration注解标注的配置类,加入到configCandidates中
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
// Return immediately if no @Configuration classes were found
if (configCandidates.isEmpty()) {
return;
}
// Sort by previously determined @Order value, if applicable
configCandidates.sort((bd1, bd2) -> {
int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
return Integer.compare(i1, i2);
});
// Detect any custom bean name generation strategy supplied through the enclosing application context
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
AnnotationConfigUtils.CONFIGURATION_BEAN_NAME_GENERATOR);
if (generator != null) {
this.componentScanBeanNameGenerator = generator;
this.importBeanNameGenerator = generator;
}
}
}
if (this.environment == null) {
this.environment = new StandardEnvironment();
}
// Parse each @Configuration class
ConfigurationClassParser parser = new ConfigurationClassParser(
this.metadataReaderFactory, this.problemReporter, this.environment,
this.resourceLoader, this.componentScanBeanNameGenerator, registry);
// 使用Set对可能发生重复的config进行去重
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.getConfigurationClasses());
configClasses.removeAll(alreadyParsed);
// Read the model and create bean definitions based on its content
if (this.reader == null) {
this.reader = new ConfigurationClassBeanDefinitionReader(
registry, this.sourceExtractor, this.resourceLoader, this.environment,
this.importBeanNameGenerator, parser.getImportRegistry());
}
// 将configClasses转化成BeanDefinition,注册到BeanFactory中
this.reader.loadBeanDefinitions(configClasses);
alreadyParsed.addAll(configClasses);
candidates.clear();
if (registry.getBeanDefinitionCount() > candidateNames.length) {
String[] newCandidateNames = registry.getBeanDefinitionNames();
Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
Set<String> alreadyParsedClasses = new HashSet<>();
for (ConfigurationClass configurationClass : alreadyParsed) {
alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
}
for (String candidateName : newCandidateNames) {
if (!oldCandidateNames.contains(candidateName)) {
BeanDefinition bd = registry.getBeanDefinition(candidateName);
if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
!alreadyParsedClasses.contains(bd.getBeanClassName())) {
candidates.add(new BeanDefinitionHolder(bd, candidateName));
}
}
}
candidateNames = newCandidateNames;
}
}
while (!candidates.isEmpty());
// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
}
if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
// Clear cache in externally provided MetadataReaderFactory; this is a no-op
// for a shared cache since it'll be cleared by the ApplicationContext.
((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
}
}
ConfigurationClassParser的parse方法
ConfigurationClassParser的parse方法完成了配置类的解析过程。
我们的BeanDefinition是AnnotatedBeanDefinition,所以接下来看下 parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
public void parse(Set<BeanDefinitionHolder> configCandidates) {
for (BeanDefinitionHolder holder : configCandidates) {
BeanDefinition bd = holder.getBeanDefinition();
try {
if (bd instanceof AnnotatedBeanDefinition) {
parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
}
else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
}
else {
parse(bd.getBeanClassName(), holder.getBeanName());
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
}
}
this.deferredImportSelectorHandler.process();
}
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
}
protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
// 根据@Conditional注解,看是否需要跳过
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
if (existingClass != null) {
if (configClass.isImported()) {
if (existingClass.isImported()) {
existingClass.mergeImportedBy(configClass);
}
// Otherwise ignore new imported config class; existing non-imported class overrides it.
return;
}
else {
// Explicit bean definition found, probably replacing an import.
// Let's remove the old one and go with the new one.
this.configurationClasses.remove(configClass);
this.knownSuperclasses.values().removeIf(configClass::equals);
}
}
// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass, filter);
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
}
while (sourceClass != null);
// 对于普通的类,加入到configurationClasses集合中,等待被loadBeanDefinition
this.configurationClasses.put(configClass, configClass);
}
可以看到,doProcessConfigurationClass方法具体处理了我们在配置类上标注的注解,例如@Component、@PropertySource、@ComponentScan、@Import以及@Bean。
/**
* Apply processing and build a complete {@link ConfigurationClass} by reading the
* annotations, members and methods from the source class. This method can be called
* multiple times as relevant sources are discovered.
* @param configClass the configuration class being build
* @param sourceClass a source class
* @return the superclass, or {@code null} if none found or previously processed
*/
@Nullable
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass, filter);
}
// Process any @PropertySource annotations
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}
else {
logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
// 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());
}
}
}
}
// Process any @Import annotations
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);
// Process any @ImportResource annotations
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
if (importResource != null) {
String[] resources = importResource.getStringArray("locations");
Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
for (String resource : resources) {
String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
configClass.addImportedResource(resolvedResource, readerClass);
}
}
// Process individual @Bean methods
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// Process default methods on interfaces
processInterfaces(configClass, sourceClass);
// Process superclass, if any
if (sourceClass.getMetadata().hasSuperClass()) {
String superclass = sourceClass.getMetadata().getSuperClassName();
if (superclass != null && !superclass.startsWith("java") &&
!this.knownSuperclasses.containsKey(superclass)) {
this.knownSuperclasses.put(superclass, configClass);
// Superclass found, return its annotation metadata and recurse
return sourceClass.getSuperClass();
}
}
// No superclass -> processing is complete
return null;
}
2.2 postProcessBeanFactory方法
整体流程
我们看下ConfigurationClassPostProcessor实现的BeanFactoryPostProcessor接口的postProcessBeanFactory方法。这个方法会把标注了@Configuration注解的配置类通过cglib进行增强,即生成代理类。此外,还会添加一个ImportAwareBeanPostProcessor的Bean实例。
/**
* Prepare the Configuration classes for servicing bean requests at runtime
* by replacing them with CGLIB-enhanced subclasses.
*/
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
int factoryId = System.identityHashCode(beanFactory);
if (this.factoriesPostProcessed.contains(factoryId)) {
throw new IllegalStateException(
"postProcessBeanFactory already called on this post-processor against " + beanFactory);
}
this.factoriesPostProcessed.add(factoryId);
if (!this.registriesPostProcessed.contains(factoryId)) {
// BeanDefinitionRegistryPostProcessor hook apparently not supported...
// Simply call processConfigurationClasses lazily at this point then.
processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
}
// 如果配置类标注了@Configuration,则将配置类对应的BeanDefinition的setClass 设置成cglib增强过的代理对象。这样在后面实例化Bean时,实例化的就是代理对象了
enhanceConfigurationClasses(beanFactory);
// 这里添加一个ImportAwareBeanPostProcessor的Bean实例
beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
}