前面我们谈到了后置处理器的加载过程,那么其中就有一个特殊的后置处理器——ConfigurationClassPostProcessor.class
;他就是在Spring启动初始化时最先注入的bdinternalConfigurationAnnotationProcessor
;由于这个类他实现了BeanDefinitionRegistryPostProcessor
接口,因此Spring在执行后置处理器的时候,会先调用该后置处理器的该接口:
// ConfigurationClassPostProcessor
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
int registryId = System.identityHashCode(registry);
this.registriesPostProcessed.add(registryId);
// ...
processConfigBeanDefinitions(registry);
}
扫描当前bd(就是Spring内部注册的bd以及手动register()的类),筛选configurationClass
字段合法的bd,将其进行排序;
bd属性字段configurationClass设置为full: 是加@Configuration;
bd属性字段configurationClass设置为lite:是加@Componnet||@ComponentScan||@Import||@ImportResource||@Bean
创建配置类分析器ConfigurationClassParse
,将上面筛选的bd依稀调用该分析器的parse();
递归处理配置类内部的成员类;
处理资源属性配置@PropertySource
;
循环扫描componentScans;
ComponentScanAnnotationParser
,调用doScan()方法,将所有扫描的类转化成bdScannedGenericBeanDefinition
,并加入bd集合中;若扫描的类中还有配置类,则继续递归解析;
处理该配置类所有的@Import,ImportBeanDefinitionRegistrar,ImportResource,内部方法,@Bean等;
通过读取器ConfigurationClassBeanDefinitionReader
将import,@Bean等注入的bd注册进bd集合中;
被引入import进来,生成bdAnnotatedGenericBeanDefinition;
@Bean,生成bdConfigurationClassBeanDefinition;
请结合流程图查看
这个方法就是ConfigurationClassPostProcessor需要重写的postProcessBeanDefinitionRegistry()中的核心方法;
首先传入的参数registry,实际上就是我们的DefaultListableBeanFactory,这个上一篇后置处理器文章有讲到;
这个方法里面我们先取出我们工厂里已有的bd,就是spring定义的6个内置bd+我们注册的启动时的类;
Spring将这7个bd判断哪些是有加配置注解的,这里看方法2,将其加入集合并进行排序;
定义了ConfigurationClassParser配置类分析器,循环将上述加配置注解的类调用配置类分析器的parse()方法;这里要跳到方法3去看;
方法3执行完后,就把初始路径下所有的类全部扫描完生成bd注入进bean工厂了,目前,@Bean,importBeanDefinitionRegistrarsMap中的类还没有注入进bd中;因此这里创建了一个ConfigurationClassBeanDefinitionReader
读取器去处理;这里调用this.reader.loadBeanDefinitions(configClasses)
见方法10;
当这些处理完,Spring再次扫描判断是否还有新的配置类,加入configCandidates集合中;
这个方法就分析完了;
// ConfigurationClassPostProcessor.class
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
String[] candidateNames = registry.getBeanDefinitionNames();
// 取出spring自己的bd和自己加的bd(入口注册的)
for (String beanName : candidateNames) {
BeanDefinition beanDef = registry.getBeanDefinition(beanName);
// 判断bd是否已经执行过checkConfigurationClassCandidate()方法 修改过bd的属性字段
if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
if (logger.isDebugEnabled()) {
logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
}
}
// bd属性字段configurationClass设置为full: 是加@Configuration
// bd属性字段configurationClass设置为lite:是加@Componnet||@ComponentScan||@Import||@ImportResource||@Bean
// 如果加了上述注解且又加了@order,该bd属性order字段设置order的值
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
// 对这些bd按照order进行排序(没有@order的其value是Integer.MAX,值越大,优先级越小)
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
// 初始进来时 registry 是DefaultListableBeanFactory类型,实现了SingletonBeanRegistry
SingletonBeanRegistry sbr = null;
if (registry instanceof SingletonBeanRegistry) {
sbr = (SingletonBeanRegistry) registry;
if (!this.localBeanNameGeneratorSet) {
// 从beanMap中取internalConfigurationBeanNameGenerator 但初始进来后,没有将该bean创建出来,因此是null
BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(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);
// 去重 就是我们之前手动注册的带有上述注解的bd
Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
// 标记已解析的class-避免重复解析
Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
do {
// 将candidates集合中的所有包含的类解析成bd注入进bean工厂
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());
}
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();
}
}
这个方法是ConfigurationClassUtils类中的方法,他是判断bd上面是否有配置类注解,如果有根据类型设置相应bd的configurationClass字段;
其中配置类注解分为两类:
除此之外,若加了@Order,则在bd中设置order值
// ConfigurationClassUtils.class
public static boolean checkConfigurationClassCandidate(BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
String className = beanDef.getBeanClassName();
if (className == null || beanDef.getFactoryMethodName() != null) {
return false;
}
// 内置注入的话是RootBeanDefinition,我们手动注入的是:AnnotatedGenericBeanDefinition
// 这里是获取bd的元数据,根据元数据判断加注解的值
AnnotationMetadata metadata;
if (beanDef instanceof AnnotatedBeanDefinition &&
className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
// Can reuse the pre-parsed metadata from the given BeanDefinition...
metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
}
else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
// Check already loaded Class if present...
// since we possibly can't even load the class file for this Class.
Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
metadata = new StandardAnnotationMetadata(beanClass, true);
}
else {
try {
MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
metadata = metadataReader.getAnnotationMetadata();
}
catch (IOException ex) {
return false;
}
}
// 根据元数据去处理,如果加了@Configuration注解,就设置bd的属性字段为full
if (isFullConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
}
// 如果加了@Component||@ComponentScan||@Import||@ImportResource||@Bean 设置配置字段为lite
else if (isLiteConfigurationCandidate(metadata)) {
beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
}
else {
return false;
}
// It's a full or lite configuration candidate... Let's determine the order value, if any.
// 若加了@Order,则设置order属性值
Integer order = getOrder(metadata);
if (order != null) {
beanDef.setAttribute(ORDER_ATTRIBUTE, order);
}
return true;
}
从方法(1)中调用进来,这里传入的是配置类bd集合,根据bd类型去解析,其解析是调用parse()方法,实际是调用processConfigurationClass()方法,这里看方法4。解析完后,该方法还去处理该配置类中所标记的延迟导入类;
当全部扫描处理完后,再去处理延迟导入的类;延迟导入的类这里就不展开介绍了,其内部就是将所有延迟导入的类DeferredImportSelectorHolder进行排序,并按group进行分类,最后依旧循环调用processImports()方法,就是方法9;
// ConfigurationClassParser.class
public void parse(Set<BeanDefinitionHolder> configCandidates) {
// 初始化延迟导入队列
this.deferredImportSelectors = new LinkedList<>();
// 循环处理配置类bd并根据bd类型进行处理
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;
}
}
// 处理延迟导入
processDeferredImportSelectors();
}
这个方法是将配置类bd进行封装解析的入口,他不仅解析它自身,如果它的内部类,他import的类,都将递归调用这个类;
它将配置类bd数据再次包装成SourceClass,然后循环调用doProcessConfigurationClass(),这里看方法5;
当方法5返回null时才结束,否则继续循环(不为null,则说明还有父类需要处理);
当全部处理完后,将配置类加入configurationClasses集合Map中;
// ConfigurationClassParser.class
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
processConfigurationClass(new ConfigurationClass(metadata, beanName));
}
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
return;
}
// 初始情况下 configurationClasses为empty
ConfigurationClass existingClass = this.configurationClasses.get(configClass);
// 初始情况下 configurationClasses为empty
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.
// 统一的源码包装类,还包含了AnnotationMetadata属性
SourceClass sourceClass = asSourceClass(configClass);
do {
sourceClass = doProcessConfigurationClass(configClass, sourceClass);
}
while (sourceClass != null);
// 将处理完的配置类class放入map中
this.configurationClasses.put(configClass, configClass);
}
这个类就是核心解析配置类的方法了。建议配合我附上的源码解析和流程图看;
它首先去处理内部类,如果其含有内部类,则判断是否是full或lite,然后再次递归调用入口函数processConfigurationClass();
将所引用的配置文件,解析到Environment中;
关于@PropertySource的使用:https://www.cnblogs.com/517cn/p/10946213.html
扫描@ComponentScans,@ComponentScan 指定的类,包路径等;这里就是核心的扫描注册进工厂的地方,通过调用this.componentScanParser.parse(),这里看方法6;这里扫描完,如果发现扫描的bd中还有配置类,则递归调用parse()方法;
componentScanParser是什么时候创建的?实际上是ConfigurationClassParser在构建函数时创建的;
this.componentScanParser = new ComponentScanAnnotationParser(environment, resourceLoader, componentScanBeanNameGenerator, registry);
上述执行完后,就将配置类所在包下的所有类全部扫描成bd加入了bean工厂中,接下来处理的是配置类上加@Import注解,这里调用processImports()方法,处理import的类,见方法9;
若配置类有使用@ImportResource,则加入configClass的(importedResources)map中;
处理定义在内部的@Bean,将其加入到configClass的(beanMethods)set中;
如果有父类,则return父类,否则return null;
// ConfigurationClassParser.class
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
throws IOException {
// Recursively process any member (nested) classes first
// 处理其中定义的内部类,是否是full或lite否则要再次递归调用processConfigurationClass
processMemberClasses(configClass, sourceClass);
// Process any @PropertySource annotations
// 当使用配置文件中的值为属性赋值的时候,通过@PropertySource导入配置文件
// 通过@PropertySource注解将properties配置文件中的值存储到Spring的 Environment中,Environment接口提供方法去读取配置文件中的值,参数是properties文件中定义的key值。
// 关于@PropertySource的使用:https://www.cnblogs.com/517cn/p/10946213.html
for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
sourceClass.getMetadata(), PropertySources.class,
org.springframework.context.annotation.PropertySource.class)) {
if (this.environment instanceof ConfigurableEnvironment) {
// 获得配置文件的Resource文件
processPropertySource(propertySource);
}
else {
logger.warn("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
"]. Reason: Environment must implement ConfigurableEnvironment");
}
}
// Process any @ComponentScan annotations
// 扫描@ComponentScans,@ComponentScan 指定的类
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
// 扫描componentScan的类加入bd中
// 它是自己new了ClassPathBeanDefinitionScanner去扫描的
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
// 检查扫描的bdh集合是否有任何的配置类,并进行递归解析
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
// 递归处理
// ImportSelector 将返回的对象继续processImports
// ImportBeanDefinitionRegistrar 加入configClass的(importBeanDefinitionRegistrars)map中
// 其余的加入configClass的(imports)map中
processImports(configClass, sourceClass, getImports(sourceClass), true);
// Process any @ImportResource annotations
// 定义的importResource加入configClass的(importedResources)map中
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
// 处理定义在内部的bean,将其加入到configClass的(beanMethods)set中
Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
for (MethodMetadata methodMetadata : beanMethods) {
configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
}
// Process default methods on interfaces
// 将方法上加了@Bean的都加入到configClass的(beanMethods)set中
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;
}
这个方法创建了一个ClassPathBeanDefinitionScanner扫描器,而不是用刚开始Spring初始化的时候定义的ClassPathBeanDefinitionScanner
;
每次扫描指定的路径时,调用该方法都会创建一个扫描器,这里面就是初始化扫描器的一些基本配置,比如bean名生成器,代理,懒加载等默认值,都是根据@ComponentScans配置的数据;
这里如果没有指定要扫描的包路径,则包路径设置为当前类所在包;这也解释了,每次启动Spring的时候,会自动扫描当前入口类所在包及其子包下的所有类;
最终调用扫描器的扫描方法;scanner.doScan()
;这里见方法7;并将扫描完的bdh集合返回;
// ComponentScanAnnotationParser.class
public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
// 设置bean名称生成器
Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
BeanUtils.instantiateClass(generatorClass));
// 若有代理则扫描器需要set代理
ScopedProxyMode scopedProxyMode = componentScan.getEnum("scopedProxy");
if (scopedProxyMode != ScopedProxyMode.DEFAULT) {
scanner.setScopedProxyMode(scopedProxyMode);
}
else {
Class<? extends ScopeMetadataResolver> resolverClass = componentScan.getClass("scopeResolver");
scanner.setScopeMetadataResolver(BeanUtils.instantiateClass(resolverClass));
}
scanner.setResourcePattern(componentScan.getString("resourcePattern"));
// 添加需要扫描的类
for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter)) {
scanner.addIncludeFilter(typeFilter);
}
}
// 添加需要过滤的类
for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
for (TypeFilter typeFilter : typeFiltersFor(filter)) {
scanner.addExcludeFilter(typeFilter);
}
}
// 判断是否需要懒加载
boolean lazyInit = componentScan.getBoolean("lazyInit");
if (lazyInit) {
scanner.getBeanDefinitionDefaults().setLazyInit(true);
}
// 获取扫描包路径
Set<String> basePackages = new LinkedHashSet<>();
String[] basePackagesArray = componentScan.getStringArray("basePackages");
for (String pkg : basePackagesArray) {
// 将指定的路径中特殊字符替换掉并加入basePackages集合中
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()) {
basePackages.add(ClassUtils.getPackageName(declaringClass));
}
scanner.addExcludeFilter(new AbstractTypeHierarchyTraversingFilter(false, false) {
@Override
protected boolean matchClassName(String className) {
return declaringClass.equals(className);
}
});
// 上面一大段都是初始化扫描器
// 这里才开始扫描
return scanner.doScan(StringUtils.toStringArray(basePackages));
}
这个方法就是实际的扫描逻辑了;
通过调用findCandidateComponents()
方法,通过ASM将包路径下的类全部扫描生成ScannedGenericBeanDefinition
并包装成bdr返回,具体看方法8;
将得到的bd进行初始化,以及配置该bean是否懒加载,依赖@DependsOn,@Primary等属性值;
bean工厂对该bd进行检查,判断是否不存在bean工厂中,就将bd注入进bean工厂中;
最终将bdh集合返回;
// ClassPathBeanDefinitionScanner.class
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
Assert.notEmpty(basePackages, "At least one base package must be specified");
Set<BeanDefinitionHolder> beanDefinitions = new LinkedHashSet<>();
for (String basePackage : basePackages) {
// 将包路径下的class转为bd
Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
for (BeanDefinition candidate : candidates) {
// 生成元数据 若有指定代理则设置元数据中代理属性
// Spring在注册bean的时候。会通过bean的作用域来决定是否使用代理模式去创建bean。如果是单例模式,那么不会使用代理,非单例就会使用。并且如果这个bean实现了接口,就会使用JDK动态代理,如果继承类,就会使用Cglib代理。
ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
// bd设置元数据
candidate.setScope(scopeMetadata.getScopeName());
// 获取bd的名称
String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
// 初始时,findCandidateComponents()扫描创建的都是ScannedGenericBeanDefinition
// 他都是实现AbstractBeanDefinition和AnnotatedBeanDefinition的
if (candidate instanceof AbstractBeanDefinition) {
// bd设置初始默认值(不懒加载,默认不注入,不进行依赖检查,无初始执行方法,无销毁执行方法)
// 以及是否设置某个bean自动注入的时候是否为作为候选bean
postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
}
if (candidate instanceof AnnotatedBeanDefinition) {
// 根据实际配置设置该bean是否懒加载,依赖@DependsOn,@Primary等属性值
AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
}
// 检测当前bf没有冲突 (判断bd是否注册,若已有bd那判断与现有bd是否冲突)
if (checkCandidate(beanName, candidate)) {
BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
definitionHolder =
AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
beanDefinitions.add(definitionHolder);
// 注册进入bean工厂
registerBeanDefinition(definitionHolder, this.registry);
}
}
}
return beanDefinitions;
}
这个方法会调用scanCandidateComponents()
方法;
它通过ASM读取包路径下的类,将合法可以转为bd类转换成bdScannedGenericBeanDefinition
;
最终将路径下的所有bd放入集合返回;
其中判断类是正常的类(不是接口或抽象类)如果是抽象类@Lookup注入也算正常类;
// ClassPathScanningCandidateComponentProvider.class
// ClassPathBeanDefinitionScanner.class是它的子类
// 这里调用的是父类的findCandidateComponents()
public Set<BeanDefinition> findCandidateComponents(String basePackage) {
if (this.componentsIndex != null && indexSupportsIncludeFilters()) {
return addCandidateComponentsFromIndex(this.componentsIndex, basePackage);
}
else {
// 初始化进入的是这里
return scanCandidateComponents(basePackage);
}
}
private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
Set<BeanDefinition> candidates = new LinkedHashSet<>();
try {
// 转换成 classpath*:${basePackage}/**/*.class
String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
resolveBasePackage(basePackage) + '/' + this.resourcePattern;
Resource[] resources = getResourcePatternResolver().getResources(packageSearchPath);
boolean traceEnabled = logger.isTraceEnabled();
boolean debugEnabled = logger.isDebugEnabled();
for (Resource resource : resources) {
if (traceEnabled) {
logger.trace("Scanning " + resource);
}
if (resource.isReadable()) {
try {
MetadataReader metadataReader = getMetadataReaderFactory().getMetadataReader(resource);
// 判断是否需要过滤
if (isCandidateComponent(metadataReader)) {
// 通过扫描的都是 ScannedGenericBeanDefinition
ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
sbd.setSource(resource);
// 判断是正常的类(不是接口或抽象类)如果是抽象类@Lookup注入也算正常类
if (isCandidateComponent(sbd)) {
if (debugEnabled) {
logger.debug("Identified candidate component class: " + resource);
}
candidates.add(sbd);
}
else {
if (debugEnabled) {
logger.debug("Ignored because not a concrete top-level class: " + resource);
}
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not matching any filter: " + resource);
}
}
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to read candidate component class: " + resource, ex);
}
}
else {
if (traceEnabled) {
logger.trace("Ignored because not readable: " + resource);
}
}
}
}
catch (IOException ex) {
throw new BeanDefinitionStoreException("I/O failure during classpath scanning", ex);
}
return candidates;
}
这个类将Import导入进来的类进行分类处理;
// ConfigurationClassParser.class
private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
Collection<SourceClass> importCandidates, boolean checkForCircularImports) {
if (importCandidates.isEmpty()) {
return;
}
if (checkForCircularImports && isChainedImportOnStack(configClass)) {
this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
}
else {
this.importStack.push(configClass);
try {
for (SourceClass candidate : importCandidates) {
// 若@Import的类实现了ImportSelector
if (candidate.isAssignable(ImportSelector.class)) {
// Candidate class is an ImportSelector -> delegate to it to determine imports
Class<?> candidateClass = candidate.loadClass();
ImportSelector selector = BeanUtils.instantiateClass(candidateClass, ImportSelector.class);
// 设置selector 的bean工厂,环境,类加载器,资源加载器
ParserStrategyUtils.invokeAwareMethods(
selector, this.environment, this.resourceLoader, this.registry);
if (this.deferredImportSelectors != null && selector instanceof DeferredImportSelector) {
this.deferredImportSelectors.add(
new DeferredImportSelectorHolder(configClass, (DeferredImportSelector) selector));
}
else {
// selector获取import的class 递归调用processImports
String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames);
processImports(configClass, currentSourceClass, importSourceClasses, false);
}
}
// 若@Import的类实现了ImportBeanDefinitionRegistrar
else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
// Candidate class is an ImportBeanDefinitionRegistrar ->
// delegate to it to register additional bean definitions
Class<?> candidateClass = candidate.loadClass();
ImportBeanDefinitionRegistrar registrar =
BeanUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class);
// 设置registrar 的bean工厂,环境,类加载器,资源加载器
ParserStrategyUtils.invokeAwareMethods(
registrar, this.environment, this.resourceLoader, this.registry);
// 加入进importBeanDefinitionRegistrarsMap中
configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
}
// 若@Import的类没有实现上述两个接口
else {
// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
// process it as an @Configuration class
// importStackMap中加入
this.importStack.registerImport(
currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
// 将他当作@Configuration 修饰的类去递归调用processConfigurationClass
processConfigurationClass(candidate.asConfigClass(configClass));
}
}
}
catch (BeanDefinitionStoreException ex) {
throw ex;
}
catch (Throwable ex) {
throw new BeanDefinitionStoreException(
"Failed to process import candidates for configuration class [" +
configClass.getMetadata().getClassName() + "]", ex);
}
finally {
this.importStack.pop();
}
}
}
这个读取器,将被@Import导入的类生成bd(AnnotatedGenericBeanDefinition
);
将@Bean创建的Bean生成bd(ConfigurationClassBeanDefinition
);
将所有的ImportBeanDefinitionRegistrar调用其registerBeanDefinitions()方法;
// ConfigurationClassBeanDefinitionReader.class
public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
for (ConfigurationClass configClass : configurationModel) {
loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
}
}
private void loadBeanDefinitionsForConfigurationClass(
ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
if (trackedConditionEvaluator.shouldSkip(configClass)) {
String beanName = configClass.getBeanName();
if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
this.registry.removeBeanDefinition(beanName);
}
this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
return;
}
// 被引入import进来
if (configClass.isImported()) {
// 生成AnnotatedGenericBeanDefinition
registerBeanDefinitionForImportedConfigurationClass(configClass);
}
for (BeanMethod beanMethod : configClass.getBeanMethods()) {
// 生成ConfigurationClassBeanDefinition
loadBeanDefinitionsForBeanMethod(beanMethod);
}
// 加载资源
loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
// 调用注册的ImportBeanDefinitionRegistrar.registerBeanDefinitions()方法
loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
}
// 将所有的ImportBeanDefinitionRegistrar调用其registerBeanDefinitions()方法
private void loadBeanDefinitionsFromRegistrars(Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> registrars) {
registrars.forEach((registrar, metadata) ->
registrar.registerBeanDefinitions(metadata, this.registry));
}