首页 > 编程学习 > BeanDefinition扫描注册过程

BeanDefinition扫描注册过程

发布时间:2022/11/14 1:01:55

文章目录

  • invokeBeanFactoryPostProcessors
  • ConfigurationClassPostProcessor
    • 内部类加载
    • 根据注解PropertySources加载额外的配置文件
    • @ComponentScan annotations
    • @ComponentScan 注解 (扫描包)
    • Import导入
    • ImportResource
    • 处理@Bean方法
        • 检查继承的接口的@Bean的方法,加入对应beanClass的 beanMethods中
    • 处理父类
    • AutoConfigurationImportSelector
    • 扫描到的configurationClasses注册到工厂
  • 执行扫描到的BeanFactoryPostProcessors接口

从refersh方法中执行invokeBeanFactoryPostProcessors(beanFactory)方法看
invokeBeanFactoryPostProcessors(beanFactory);
看方法名就知道,执行BeanFactoryPostProcessors接口

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
		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()));
		}
	}

invokeBeanFactoryPostProcessors

invokeBeanFactoryPostProcessors
这个方法会实例化和调用所有BeanFactoryPostProcessor,包括其子类BeanDefinitionRegistryPostProcessor。
BeanFactoryPostProcessor接口是Spring初始化BeanFactory时对外暴露的扩展点,Spring IOC容器允许BeanFactoryPostProcessor在容器实例化bean之前读取并修改bean定义。
注意:BeanDefinitionRegistryPostProcessor继承BeanFactoryPostProcessor,比BeanFactoryPostProcessor具有更高的优先级

BeanFactoryPostProcessors有三种情况:
1、我们手动注册
2、Spring扫描出来的
3、Spring自定义的
什么是手动注册的?
就是我们手动调用AnnotationConfigApplicationContext.addBeanFactoryPostProcessor();这个方法添加的。
什么是Spring扫描出来的?
我们自己实现了BeanFactoryPostProcessor接口的类可以加@Companent,也可以不加,如果加了那么就属于是Spring扫描出来的。
什么是Spring自定义的?
在Spring内容也有其实现类BeanFactoryPostProcessor接口的类,它会自己去获取出来,我们不用管。

那么看其执行流程

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
 
		// Invoke BeanDefinitionRegistryPostProcessors first, if any.
		Set<String> processedBeans = new HashSet<>();
 
		//先执行(beanFactory)容器的 BeanDefinitionRegistryPostProcessor.postProcessBeanDefinitionRegistry()方法
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//都是放程序员自己添加的 BeanFactoryPostProcessor  BeanDefinitionRegistryPostProcessor
			//regularPostProcessors 常规的后置处理器
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
 
			//这个for用来区分 BeanDefinitionRegistryPostProcessor 和 BeanFactoryPostProcessor
			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					//执行自己手动加进去的
					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.
			// 放的是 spring 内部自己实现了 BeanDefinitionRegistryPostProcessor 接口的类
			//ConfigurationClassPostProcessor 就是spring自己的  目前来说只有一个:ConfigurationClassPostProcessor
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
 
			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			//获取容器中 所有的 BeanDefinitionRegistryPostProcessor
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			// 第一优先级 先执行实现了 PriorityOrdered 优先级接口的 BeanDefinitionRegistryPostProcessor
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					//把要执行的 BeanDefinitionRegistryPostProcessor 放在 currentRegistryProcessors 集合中
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					//把要执行的 postProcessorName 放在 processedBeans 集合中
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			//把自己手动调用方法添加的 BeanDefinitionRegistryPostProcessor 与 spring内部的合并
			registryProcessors.addAll(currentRegistryProcessors);
			//执行 spring 内部的 beanDefinitionRegistryPostProcessor
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();
 
			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			// 第二优先级 执行实现了 Ordered 顺序接口的 BeanDefinitionRegistryPostProcessor
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				//在之前的 执行过的postProcessorName中不包含当前的名称,且类型是 Ordered 的
				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.
			// 最后执行没有实现 PriorityOrdered 、 Ordered 接口的 BeanDefinitionRegistryPostProcessor
			boolean reiterate = true;
			while (reiterate) {
				reiterate = false;
				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.
			// 执行 实现了 postProcessBeanFactory.postProcessBeanFactory() 的方法
			//只是将父子类分开执行了,先子类后父类
			// 这里只执行 BeanFactoryPostProcessor 中的 postProcessBeanFactory 方法
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			//处理常规的后置处理器,BeanFactoryPostProcessor
			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!
		//这里执行实现了 BeanFactoryPostProcessor 接口的 postProcessBeanFactory() 方法
		// 就是  BeanFactoryPostProcessor 在 BeanDefinitionRegistryPostProcessor 之后执行
		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<>();
		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<>();
		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();
	}

这里第一步进行了一个判断:
在这里插入图片描述
我在这里说一下,这里传过来的的beanFactory其实是:DefaultListableBeanFactory
DefaultListableBeanFactory继承自BeanDefinitionRegistry条件成立才会执行

接着向下看
首先执行程序员自己放进入的BeanPostProcess
在这里插入图片描述

现在我们知道第一个if判断是正确的,进入这个if语句里,
1、将当前beanFactory类型为BeanDefinitionRegistry类型。
2、定义两个List,其中:regularPostProcessors代表的是BeanFactoryPostProcessor类型的,registryProcessors代表的是BeanDefinitionRegistryPostProcessor类型的。
为什么要定义两个List?
因为我们可以实现,BeanFactoryPostProcessor,也可以实BeanDefinitionRegistryPostProcessor
我们将实现了这两个类的后置处理器手动注册到了beanFactoryPostProcessors(以参数的形式传过来的),由于这两个类的执行时期不同,所以我们需要将这两种类型的处理器分开处理。
在这个for循环里,如果是实现了BeanDefinitionRegistryPostProcessor的类,则将当前这个类放入到registryProcessors集合当中,否则就是实现了BeanFactoryPostProcessor的类,将它放入到regularPostProcessors集合当中。
我们接着往下看:Spring又定义了一个List,这个List用于存放Spring自己添加的BeanDefinitionRegistryPostProcessor类,之后根据BeanDefinitionRegistryPostProcessor类型来获取所有实现了此类型的beanName。
在这里插入图片描述

其实这个postProcessorNames只有一个类,那就是我们的ConfigurationClassPostProcessor类

	      sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			currentRegistryProcessors.clear();

首先排序,同样时根据@Order注解和PriorityOrdered接口进行排序。
将spring内置的ConfigurationClassPostProcessor与用户后动注册的合并到registryProcessors
后开始执行ConfigurationClassPostProcessor

ConfigurationClassPostProcessor

这是一个十分重要的类。bean的扫描由此类完成

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

		for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
			postProcessor.postProcessBeanDefinitionRegistry(registry);
		}
	}

执行BeanDefinitionRegistryPostProcessor接口的postProcessBeanDefinitionRegistry方法
那么就来到了ConfigurationClassPostProcessor的postProcessBeanDefinitionRegistry方法
进入了一个非常重要的方法
processConfigBeanDefinitions(registry); 这个方法非常非常重要,我们来看看这个方法里都做了哪些事情。我先贴一下这个方法的全部代码:

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		// app提供的bean
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
		// 获取容器中 注册的 所有 容器的名字
		String[] candidateNames = registry.getBeanDefinitionNames();
 
		for (String beanName : candidateNames) {
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
			//配置类的类型标记判断
			if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
					ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
			//判断是否是一个配置 beanDefinition加了@configrution,@Component,@import 等等
			//并且设置配置db的类型标记:
			// 1.full @configrution
			// 2.lite @Component,@ComponentScan,@import,@ImportResource
			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(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<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
		Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
		do {
			//主要做扫描包,扫描出来的类放在parser中,在下面统一进行注册到容器
			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());
			}
			//把扫描出来的 db 注册到容器中,
			// 包括ImportSelector,ImportBeanDefinitionRegistrar
			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();
		}
	}

我们来一步一步第分析 processConfigBeanDefinitions
1、先定义一个List configCandidates 用于存放交给Spring管理的bean。

List<BeanDefinitionHolder> configCandidates = new ArrayList<>();

2、获取容器中所有已注册的bean的名字

// 获取容器中 注册的 所有 容器的名字
String[] candidateNames = registry.getBeanDefinitionNames();

3、遍历所有已经注册的bean
3.1、根据beanName获取Bean定义:beanDef
3.2、第一个if,判断当前bean是不是已经处理过(当前是第一次进,肯定没有处理过),那么会进else if,这个if判断当前bean是不是一个加了
@Configuration,@Component,@ComponentScan,@Import,@ImportResource注解,如果加了这些注解那么该bean会被加入configCandidates
将当前这个bean封装成BeanDefinitionHolder,放进最开始定义的:configCandidates当中。
在这里插入图片描述

    //根据古@Order注解对configCandidates顺序调整
		configCandidates.sort((bd1, bd2) -> {
			int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
			int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
			return Integer.compare(i1, i2);
		});

/
我们接着往下看:创建一个解析器,用来解析配置信息

		ConfigurationClassParser parser = new ConfigurationClassParser(
				this.metadataReaderFactory, this.problemReporter, this.environment,
				this.resourceLoader, this.componentScanBeanNameGenerator, registry);

重点:

//去重
		Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
		Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
		do {
			//主要做扫描包,扫描出来的类放在parser中,在下面统一进行注册到容器
			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());
			}
			//把扫描出来的 db 注册到容器中,
			// 包括ImportSelector,ImportBeanDefinitionRegistrar
			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());

定义两个set集合:
第一个Set:将符合条件的bean去重,Spring害怕你提供了多个相同的bean,所以这里进行了去除。
第二个Set:现在先不说。

    Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);		    
    Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());

我们接着往下看进入到do … while循环:
在这里插入图片描述

先来做包扫描(configClasses 这个说的是配置类,加了@configuration注解的类也就是我们的Appconfig类)
点开这个方法:
在这里插入图片描述

1、循环解析配置类(可能存在多个)
2、获取我们的BeanDefinition ,判断是哪种bean,不同的bean解析方式不同,我们以入口类为例,此时的bean肯定是加了注解的bean ,所以一地个if语句符合,点击parse()方法:

protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
		processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
	}

接着看
在这里插入图片描述

当前类为AppConfig类也就是我们的配置类。

第一、判断当前类是哦福需要跳过解析,通过conditionEvaluator
第二、判断是否被其他类加了@import
第三、do…while 循环处理配置类
将配置类转换为 SourceClass 这里理解成从此bean开始递归扫描其他的bean。
do…while循环处理配置类,我们点开doProcessConfigurationClass这个方法:

protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
		throws IOException {
// 如果标注了@Component注解,则首先尝试处理成员类(内部类)
	if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
		// Recursively process any member (nested) classes first
		processMemberClasses(configClass, sourceClass);
	}

	// Process any @PropertySource annotations
	// 解析@PropertySource注解,将会添加配置信息到环境中
	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
	// 解析@ComponentScan注解,使用ComponentScanAnnotationParser解析器
	// 扫描@Configuration、@Service、@Controller、@Repository和@Component注解并注册BeanDefinition
	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
			//获取扫描解析到的BeanDefinition
			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
			// 对scannedBeanDefinitions遍历,检测是否为候选配置类,触发parse
			//也就是对扫描到的类再次触发解析过程,递归解析
			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
// 解析@Import注解,然后进行实例化,并执行ImportBeanDefinitionRegistrar的
//registerBeanDefinitions逻辑,或者ImportSelector的selectImports逻辑 或者再次触发解析
	processImports(configClass, sourceClass, getImports(sourceClass), true);

	// Process any @ImportResource annotations
	// 解析@ImportResource注解,并加载相关配置信息
	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中Set<BeanMethod> beanMethods里
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	// Process default methods on interfaces
	// 解析其实现接口中标注了@Bean注解的方法并注册到configclass中Set<BeanMethod> beanMethods里
	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;
}

内部类加载

importStack看名字是一个栈,栈顶是正在处理的元素,对于每个数据,他之后的数据 都是被他直接或者间接依赖的数据,如果当前元素已经存在栈中,报CircularImportProblem错误,
加入新元素之后,再以新元素为开始,开启新一轮的扫描

for (SourceClass candidate : candidates) {
				if (this.importStack.contains(configClass)) {
					this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
				}
				else {
					this.importStack.push(configClass);
					try {
						processConfigurationClass(candidate.asConfigClass(configClass), filter);
					}
					finally {
						this.importStack.pop();
					}
				}
			}

继续向下看

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");
			}
		}

根据注解PropertySources加载额外的配置文件

简单介绍@PropertySource
@PropertySource + @Value

package com.huang.pims.demo.props;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

@Component
@PropertySource(value = {"demo/props/demo.properties"})
public class ReadByPropertySourceAndValue {

    @Value("${demo.name}")
    private String name;

    @Value("${demo.sex}")
    private int sex;

    @Value("${demo.type}")
    private String type;

    @Override
    public String toString() {
        return "ReadByPropertySourceAndValue{" +
                "name='" + name + '\'' +
                ", sex=" + sex +
                ", type='" + type + '\'' +
                '}';
    }
}


因此PropertySource指定的配置文件也会被加载,但优先级低,而且可以自定义

在继续向下看

@ComponentScan annotations

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

@ComponentScan 注解 (扫描包)

在这里插入图片描述
我们来看这个this.componentScanParser.parse()方法:

//处理 @ComponentScan 注解 (扫描包)
	public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
 
		//这里的扫描器是spring内部用的,AnnotationConfigApplicationContext类中的扫描器是提供给外部使用的
		ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
				componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);
		//beanName生成器
		Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
		boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
		scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
				BeanUtils.instantiateClass(generatorClass));
 
		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) {
			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));
	}

请看这段代码的第一局话:在这里首先创建了一个 扫描器:

//这里的扫描器是spring内部用的,AnnotationConfigApplicationContext类中的扫描器是提供给外部使用的
ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
				componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

这个扫描器在实例化好像还在别的地方看到过,那就是AnnotationConfigApplicationContext的构造方法里:
在这里插入图片描述

这说明,我们外部调用的这个扫描器,不是Spring执行的扫描器,Spring要执行的扫描器是自己又创建了一个,所以我这里注释里说到,这个基本用不到。

//扫描
return scanner.doScan(StringUtils.toStringArray(basePackages));

我们点开这个doScan()方法,内容如下:

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) {
			//真正去扫描的,找组件,asm去扫描的
			Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
 
			for (BeanDefinition candidate : candidates) {
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				//eg: singleton prototype
				candidate.setScope(scopeMetadata.getScopeName());
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
				if (candidate instanceof AbstractBeanDefinition) {
					//设置默认值,比如没有加@lazy,则设置lazy的默认值
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
				if (candidate instanceof AnnotatedBeanDefinition) {
					//处理注解,比如加了@lazy,设置lazy的值
					// @Primary @DependsOn @Role @Description
					AnnotationConfigUtils.processCommonDefinitionAnnotations((AnnotatedBeanDefinition) candidate);
				}
				if (checkCandidate(beanName, candidate)) {
					BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(candidate, beanName);
					definitionHolder =
							AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
					beanDefinitions.add(definitionHolder);
					//加入到 map 中
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}

主要在findCandidateComponents的scanCandidateComponents方法中

	private Set<BeanDefinition> scanCandidateComponents(String basePackage) {
		Set<BeanDefinition> candidates = new LinkedHashSet<>();
		try {
			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 sbd = new ScannedGenericBeanDefinition(metadataReader);
							sbd.setSource(resource);
							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;
	}

扫描路径下的@Component注解
这个方法完成的内容是:利用asm框架,将扫描包下的类,将其转换为BeanDefinition,而后遍历,扫描出来的beanDefinition,设置bean的作用域,是否是懒加载的,处理注解信息,最后将处理好的beanDefinition放入到beanFactory当中

到这里就已经完成:扫描包,将扫描出来的类放入bean工厂。
现在我们回到:ConfigurationClassParser类的doProcessConfigurationClass()方法:
对于扫描出来的 bean定义,还会判断如果时配置类,那么还会以这个配置类为基础,开始新一轮的扫描。因此被component扫描到的包Config类也会生效

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

Import导入

processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

处理当前bean@Import注解,跟内部类逻辑相似通过importStack 进行bean的加载
还有一个功能是处理ImportSelector接口
ImportSelector介绍
在@Configuration标注的Class上可以使用@Import引入其它的配置类,其实它还可以引入org.springframework.context.annotation.ImportSelector实现类。ImportSelector接口只定义了一个selectImports(),用于指定需要注册为bean的Class名称。当在@Configuration标注的Class上使用@Import引入了一个ImportSelector实现类后,会把实现类中返回的Class名称都定义为bean。来看一个简单的示例,假设现在有一个接口HelloService,需要把所有它的实现类都定义为bean,而且它的实现类上是没有加Spring默认会扫描的注解的,比如@Component、@Service等。
例如

public class HelloImportSelector implements ImportSelector {

    @Override
    public String[] selectImports(AnnotationMetadata importingClassMetadata) {
        return new String[] {HelloServiceA.class.getName(), HelloServiceB.class.getName()};
    }

}

那么HelloServiceA,HelloServiceB也会成为bean

ImportResource

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

@ImportResource注解用于导入Spring的配置文件,让配置文件里面的内容生效;(就是以前写的springmvc.xml、applicationContext.xml)
Spring Boot里面没有Spring的配置文件,我们自己编写的配置文件,也不能自动识别;
想让Spring的配置文件生效,加载进来;@ImportResource标注在一个配置类上。
注意!这个注解是放在主入口函数的类上,而不是测试类上

不使用@ImportResource()注解,程序根本不能对我们spring的配置文件进行加载,所以我们需要将spring配置文件加载到容器里
使用springBoot不使用配置文件可以以进行配置,当然也可以不指定

处理@Bean方法

	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
		for (MethodMetadata methodMetadata : beanMethods) {
			configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
		}

这里没做更多的操作,仅仅把方法查找出来,放入beanMethods中


		// Process default methods on interfaces
		processInterfaces(configClass, sourceClass);

检查继承的接口的@Bean的方法,加入对应beanClass的 beanMethods中

private void processInterfaces(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
		for (SourceClass ifc : sourceClass.getInterfaces()) {
			Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(ifc);
			for (MethodMetadata methodMetadata : beanMethods) {
				if (!methodMetadata.isAbstract()) {
					// A default method or other concrete method on a Java 8+ interface...
					configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
				}
			}
			processInterfaces(configClass, ifc);
		}
	}

处理父类

	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();
			}
		}
	do {
			sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
		}
		while (sourceClass != null);

如果有父类,那么返回父类,从父类开始开始新一轮的bean扫描。可见,在bean扫描这上面,子类是继承父类的注解配置的
processConfigurationClass方法中最后回把处理完毕的类放到configurationClasses中

this.configurationClasses.put(configClass, configClass);

parse方法执行完毕后,也就是当前配置类已经扫描完毕的情况下,最后执行DeferredImportSelector

	this.deferredImportSelectorHandler.process();

AutoConfigurationImportSelector

会对spring.factories中的 EnableAutoConfiguration进行Import

public void processGroupImports() {
			for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
				Predicate<String> exclusionFilter = grouping.getCandidateFilter();
				grouping.getImports().forEach(entry -> {
					ConfigurationClass configurationClass = this.configurationClasses.get(entry.getMetadata());
					try {
						processImports(configurationClass, asSourceClass(configurationClass, exclusionFilter),
								Collections.singleton(asSourceClass(entry.getImportClassName(), exclusionFilter)),
								exclusionFilter, false);
					}
					catch (BeanDefinitionStoreException ex) {
						throw ex;
					}
					catch (Throwable ex) {
						throw new BeanDefinitionStoreException(
								"Failed to process import candidates for configuration class [" +
										configurationClass.getMetadata().getClassName() + "]", ex);
					}
				});
			}
		}

会对spring.factories中的配置类挨个进行执行processImports,也就每个配置类都会进入processConfigurationClass开始新一轮的递归扫描bean

扫描到的configurationClasses注册到工厂

前面扫描的类都放到了configurationClasses中

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);
	public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
		TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
		for (ConfigurationClass configClass : configurationModel) {
			loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
		}
	}

挨个注册到bean工厂中

执行扫描到的BeanFactoryPostProcessors接口

开始的时候说
BeanFactoryPostProcessors有三种情况:
1、我们手动注册
2、Spring扫描出来的
3、Spring自定义的
现在经过ConfigurationClassPostProcessor已经扫描完毕,会扫描出一批BeanFactoryPostProcessors
那么接下来invokeBeanFactoryPostProcessors方法中会继续执行BeanFactoryPostProcessors

Copyright © 2010-2022 dgrt.cn 版权所有 |关于我们| 联系方式