To find all qualified business beans, first we need to know what kind of beans are qualified in Spring and need containers to manage them:
- Bean s (@Controller, @Service, @Repository, @Component) annotated with components are used in general projects.
- Use the @Bean annotation standard method, which is typically used when importing third-party components.
- Bean s imported with the @Import annotation are typically used when quickly importing a batch of components.
Parsing of the doProcessConfigurationClass configuration class
Call Link:
doProcessConfigurationClass:289, ConfigurationClassParser (org.springframework.context.annotation) processConfigurationClass:247, ConfigurationClassParser (org.springframework.context.annotation) parse:200, ConfigurationClassParser (org.springframework.context.annotation) parse:169, ConfigurationClassParser (org.springframework.context.annotation) processConfigBeanDefinitions:308, ConfigurationClassPostProcessor (org.springframework.context.annotation) postProcessBeanDefinitionRegistry:228, ConfigurationClassPostProcessor (org.springframework.context.annotation) invokeBeanDefinitionRegistryPostProcessors:272, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:92, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:687, AbstractApplicationContext (org.springframework.context.support) refresh:525, AbstractApplicationContext (org.springframework.context.support) <init>:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
Source code:
// Resolve Configuration Class to Register Definition BeanDefinition of Business Bean into Container protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException { // Recursively process any member (nested) classes first processMemberClasses(configClass, sourceClass); // 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.warn("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), true); // Process any @ImportResource annotations if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) { AnnotationAttributes importResource = AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class); 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.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; }
From the source code we can see the complete process of parsing the configuration class:
- Working with nested classes recursively
- Processing the @PropertySource annotation, parsing the configuration file, loading the configuration item into the environment variable
- Process the @ComponentScan annotation to register all Bean Definitions that meet the criteria to the container
- Handle @Import annotations
- Handle @ImportResource annotations
- Processing the @Bean method
- Default method for handling interfaces
- Working with parent classes
Processing @ComponentScan annotations
Here we will focus on the processing of the @ComponentScan annotation. Finally, the main processing method is the ClassPathBeanDefinitionScanner#doScan() method.
Call Link:
doScan:270, ClassPathBeanDefinitionScanner (org.springframework.context.annotation) parse:135, ComponentScanAnnotationParser (org.springframework.context.annotation) doProcessConfigurationClass:289, ConfigurationClassParser (org.springframework.context.annotation) processConfigurationClass:247, ConfigurationClassParser (org.springframework.context.annotation) parse:200, ConfigurationClassParser (org.springframework.context.annotation) parse:169, ConfigurationClassParser (org.springframework.context.annotation) processConfigBeanDefinitions:308, ConfigurationClassPostProcessor (org.springframework.context.annotation) postProcessBeanDefinitionRegistry:228, ConfigurationClassPostProcessor (org.springframework.context.annotation) invokeBeanDefinitionRegistryPostProcessors:272, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:92, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:687, AbstractApplicationContext (org.springframework.context.support) refresh:525, AbstractApplicationContext (org.springframework.context.support) <init>:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
Source code:
// @ComponentScan performs package scanning protected Set<BeanDefinitionHolder> doScan(String... basePackages) { Assert.notEmpty(basePackages, "At least one base package must be specified"); Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<BeanDefinitionHolder>(); for (String basePackage : basePackages) { // Find the business beans that need to be loaded into the container based on the package path 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); // Register qualified Bean definitions into containers registerBeanDefinition(definitionHolder, this.registry); } } } return beanDefinitions; } // Find the business beans that need to be loaded into the container based on the package path public Set<BeanDefinition> findCandidateComponents(String basePackage) { Set<BeanDefinition> candidates = new LinkedHashSet<BeanDefinition>(); try { // Load into container class file as required by package path String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX + resolveBasePackage(basePackage) + '/' + this.resourcePattern; // Load all class files in the corresponding package path to memory based on the resource loader Resource[] resources = this.resourcePatternResolver.getResources(packageSearchPath); boolean traceEnabled = logger.isTraceEnabled(); boolean debugEnabled = logger.isDebugEnabled(); for (Resource resource : resources) { if (traceEnabled) { logger.trace("Scanning " + resource); } // Determine if it is readable if (resource.isReadable()) { try { MetadataReader metadataReader = this.metadataReaderFactory.getMetadataReader(resource); // Determine if it is a @Component component if (isCandidateComponent(metadataReader)) { ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader); sbd.setResource(resource); sbd.setSource(resource); if (isCandidateComponent(sbd)) { if (debugEnabled) { logger.debug("Identified candidate component class: " + resource); } candidates.add(sbd); } ... return candidates; } // Determine if it is a @Component component protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException { // Execute excludeFilters for (TypeFilter tf : this.excludeFilters) { if (tf.match(metadataReader, this.metadataReaderFactory)) { return false; } } // Execute includeFilters for (TypeFilter tf : this.includeFilters) { if (tf.match(metadataReader, this.metadataReaderFactory)) { return isConditionMatch(metadataReader); } } return false; }
The findCandidateComponents method eventually calls the hasAnnotation and hasMetaAnnotation methods of the AnnotationMetadataReadingVisitor class to determine if it is a @Component component. Call Link:
hasMetaAnnotation:112, AnnotationMetadataReadingVisitor (org.springframework.core.type.classreading) matchSelf:86, AnnotationTypeFilter (org.springframework.core.type.filter) match:61, AbstractTypeHierarchyTraversingFilter (org.springframework.core.type.filter) isCandidateComponent:354, ClassPathScanningCandidateComponentProvider (org.springframework.context.annotation) findCandidateComponents:288, ClassPathScanningCandidateComponentProvider (org.springframework.context.annotation) doScan:272, ClassPathBeanDefinitionScanner (org.springframework.context.annotation) parse:135, ComponentScanAnnotationParser (org.springframework.context.annotation) doProcessConfigurationClass:289, ConfigurationClassParser (org.springframework.context.annotation) processConfigurationClass:247, ConfigurationClassParser (org.springframework.context.annotation) parse:200, ConfigurationClassParser (org.springframework.context.annotation) parse:169, ConfigurationClassParser (org.springframework.context.annotation) processConfigBeanDefinitions:308, ConfigurationClassPostProcessor (org.springframework.context.annotation) postProcessBeanDefinitionRegistry:228, ConfigurationClassPostProcessor (org.springframework.context.annotation) invokeBeanDefinitionRegistryPostProcessors:272, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:92, PostProcessorRegistrationDelegate (org.springframework.context.support) invokeBeanFactoryPostProcessors:687, AbstractApplicationContext (org.springframework.context.support) refresh:525, AbstractApplicationContext (org.springframework.context.support) <init>:84, AnnotationConfigApplicationContext (org.springframework.context.annotation)
Source code:
// Determine if it is a @Component component public class AnnotationMetadataReadingVisitor extends ClassMetadataReadingVisitor implements AnnotationMetadata { ... // Determine whether it is a business Bean @Override public boolean hasAnnotation(String annotationName) { return this.annotationSet.contains(annotationName); } // Determine whether it is a business Bean @Override public boolean hasMetaAnnotation(String metaAnnotationType) { // If the business Bean is annotated with @Service, then in metaAnnotationMap the // org.springframework.stereotype.Service=org.springframework.stereotype.Component, // Map the @Service annotation to the @Component annotation.Other treatments inherited from the @Component annotation are the same Collection<Set<String>> allMetaTypes = this.metaAnnotationMap.values(); for (Set<String> metaTypes : allMetaTypes) { if (metaTypes.contains(metaAnnotationType)) { return true; } } return false; } ... }
Execution process:
- Find all eligible class files based on the package scope configured by the @ComponentScan annotation
- Load all class files into memory based on the resource loader
- Loop through class es to find qualified @Component components
- Execute excludeFilters for @ComponentScan
- Execute IncudeFilters for @ComponentScan
- Get the metaAnnotationMap of the current class to determine if it is a @Component component
- Register BeanDefinition of eligible class es into containers
If the business Bean is annotated with @Service, it will be stored in metaAnnotationMap as org.springframework.stereotype.Service=org.springframework.stereotype.Component, mapping the @Service annotation to the @Component annotation.Other treatments inherited from the @Component annotation are the same