在这之前我们先要了解一下ConfigurationClassPostProcessor这个类,它实现了PriorityOrdered,BeanDefinitionRegistryPostProcessor等接口

public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {

ConfigurationClassPostProcessor的类图如下:

深入解析spring的@Component注解扫描_spring

在AbstractApplicationContext中的refresh方法中,执行invokeBeanFactoryPostProcessors方法,开篇提到的ConfigurationClassPostProcessor 是 BeanFactoryPostProcessor的子类,所以

postProcessBeanFactory(beanFactory);
StartupStep beanPostProcess = this.applicationStartup.start("spring.context.beans.post-process");
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);

// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);

让我们结合下面的类图来走这个invokeBeanFactoryPostProcessors方法,先判断beanFactory 是否是BeanDefinitionRegistry的实例,结合下面的类图,成立

public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

// Invoke BeanDefinitionRegistryPostProcessors first, if any.
Set<String> processedBeans = new HashSet<>();

//判断是否是beanFactory 是否是BeanDefinitionRegistry的实例
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

进入 if 语句,先取出所有的实现了BeanDefinitionRegistryPostProcessor接口的bean,在过滤出实现 了PriorityOrdered 接口的bean,由上面的ConfigurationClassPostProcessor的类图,我们可以知道ConfigurationClassPostProcessor是满足这个条件的。

List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

// 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();

深入解析spring的@Component注解扫描_spring_02

private static void invokeBeanDefinitionRegistryPostProcessors(
Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {

for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
StartupStep postProcessBeanDefRegistry = applicationStartup.start("spring.context.beandef-registry.post-process")
.tag("postProcessor", postProcessor::toString);
postProcessor.postProcessBeanDefinitionRegistry(registry);
postProcessBeanDefRegistry.end();
}
}

当postProcessor = ConfigurationClassPostProcessor时,进入相应的实现类

深入解析spring的@Component注解扫描_spring_03

@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);

this.registriesPostProcessed.add(registryId);
//处理配置类的定义信息
processConfigBeanDefinitions(registry);
}

进入方法,默认获取到的是6个spring内部类和一个启动类

String[] candidateNames = registry.getBeanDefinitionNames();
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
//判断BeanDefinition的中attrabutes属性里是否有configurationClass属性值是否为full或者lite或者null,
//如果是full则代表是@Configuration修饰的配置类,lite代表是Component,ComponentScan,Import,ImportResource修饰的类或者有Bean修饰的方法
if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {

}
//检测是否添加了@Configuration注解,只有启动类才有这个注解
else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
}
}
//对启动类进行解析
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
parser.parse(candidates);

深入解析spring的@Component注解扫描_类图_04

递归的查询出启动类包含的所有注解

// Recursively process the configuration class and its superclass hierarchy.
SourceClass sourceClass = asSourceClass(configClass, filter);
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
}
while (sourceClass != null);

this.configurationClasses.put(configClass, configClass);

进入 ConfigurationClassParser的doProcessConfigurationClass方法 ,发现对@PropertySource ,@ComponentScan,@Bean , @Import, @ImportResource注解进行了处理

@Nullable
protected final SourceClass doProcessConfigurationClass(
ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
throws IOException {
//处理加了@Component注解所在类的成员变量
if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
// Recursively process any member (nested) classes first
processMemberClasses(configClass, sourceClass, filter);
}

// 处理添加了注解@PropertySource
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
processPropertySource(propertySource);
}

}

// 处理 @ComponentScan ,ComponentScans 注解
Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);

// 处理@Import注解
processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

//处理 @ImportResource 注解
AnnotationAttributes importResource =
AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);

//处理单独的 @Bean 方法上的注解
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}

// 处理接口中默认的方法
processInterfaces(configClass, sourceClass);

// 处理父类,在递归处理
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();
}
}

// 没有父类,处理结束,结束递归
return null;
}

扫描@Component注解

启动类继承了来自@SpringBootApplication注解的所有注解,其中有@ComponentScan,也就是对@Component进行扫描

@SpringBootApplication
public class SpringSourceApplication {

public static void main(String[] args) {
SpringApplication.run(SpringSourceApplication.class, args);
}
}

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

进入到扫描@Componen的代码区域,扫描也是要有一个范围的,比如扫描一个包,或者多个包,现在还不知道,看spring是则么处理的

// 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) {
// 执行扫描
Set<BeanDefinitionHolder> scannedBeanDefinitions =
this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());

先获取@ComponentScan注解的属性

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Repeatable(ComponentScans.class)
public @interface ComponentScan {

@AliasFor("basePackages")
String[] value() default {};

@AliasFor("value")
String[] basePackages() default {};

Class<?>[] basePackageClasses() default {};

Filter[] includeFilters() default {};

Filter[] excludeFilters() default {};
........

我们看到了basePackages属性,在启动类的@SpringBootApplication注解中并没有对basePackages进行指定,默认为空

@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),

进入​​this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName())​​ 方法,里面是对注解属性进行处理,其中就有我们关注的basePackages

Set<String> basePackages = new LinkedHashSet<>();
String[] basePackagesArray = componentScan.getStringArray("basePackages");
for (String pkg : basePackagesArray) {
String[] tokenized = StringUtils.tokenizeToStringArray(this.environment.resolvePlaceholders(pkg),
ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS);
Collections.addAll(basePackages, tokenized);
}
for (Class<?> clazz : componentScan.getClassArray("basePackageClasses")) {
basePackages.add(ClassUtils.getPackageName(clazz));
}
//满足这个条件,
if (basePackages.isEmpty()) {
//ClassUtils.getPackageName(declaringClass)是获取当前类所在的包路径,这里就是为什么把类放在启动类包外,无法扫描到的原因
basePackages.add(ClassUtils.getPackageName(declaringClass));
}
//真正开始对包进行扫描
return scanner.doScan(StringUtils.toStringArray(basePackages));

进入ClassPathBeanDefinitionScanner 的 ​​doScan(String... basePackages)​​ 方法

protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
for (String basePackage : basePackages) {
//获取所有加了@Component的 BeanDefinition
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
candidate.setScope(scopeMetadata.getScopeName());
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
if (candidate instanceof AbstractBeanDefinition) {
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
//把所有的BeanDefinition注册到BeanDefinitionRegistry中
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}

1、先扫描启动类所在包下的所有class文件
2、获取直接或者间接加了@Component注解的class文件,并包装成BeanDefinition,在包装成BeanDefinitionHolder
3、通过BeanDefinitionRegistry进行注册