Spring源码解析(18)之refresh(6)-ConfigurationPostProcessor源码分析

一、前言

        我们在上一篇的博客最后有提到了ConfigurationClassPostPorcessor,我们上节博客有说到之前Spring配置文件需要支持注解的时候只要在Spring配置文件中加入:

<context:component-scan base-package="com.springframework.configrationclass"></context:component-scan>

        在上节也带大家看了这个标签对应的解析类,解析类中主要去扫描对应的package,然后给我们注入ConfigurationClassPostPorcessor,这个类实现了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,如果大家对于这两个类还不是很熟悉的话,大家可以先移步:Spring源码解析(17)之refresh(5)-BeanFactoryPostProcessor执行流程源码分析_jokeMqc的博客-CSDN博客

去了解对应 BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor的区别以及他们的执行流程。

        好了接下来我们分析ConfigurationClassPostProcessor源码,因为他实现了BDRPP所以我们从他的postProcessBeanDefinitionRegistry方法入手:

	public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
		int registryId = System.identityHashCode(registry);
		if (this.registriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanDefinitionRegistry already called on this post-processor against " + registry);
		}
		if (this.factoriesPostProcessed.contains(registryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + registry);
		}
		// 将马上要处理的registry对象的唯一标识id放入到已经处理的集合对象中,防止重复执行
		this.registriesPostProcessed.add(registryId);

		// 解析配置类中的Bean定义.
		processConfigBeanDefinitions(registry);
	}

         这没做啥,只是生成一个唯一标记位防止重复执行,我们继续往下看他的processConfigBeanDefinitions方法去看他是如何解析配置类的。

        看到源码不要慌,我把processConfigBeanDefinitions这个方法大概做了哪些事情说下:

  1. 首先创建一个空集合来保存对应解析出来的对象,一个BeanDefinitionHolder类型的对应,BeanDefinitionHolder我们知道他是BenaDefiniton的一个持有器,里面主要包括了BeanDefinition,BeanName,Alias等信息。
  2. 我们获取现在现在已经注册到容器中的所有bean的名称,然后循环这些名称,首先先判断这些类是否已经解析过(通过BeanDefiniton里面是否存在属性来判断),然后判断这些Beandefiniton中是否存在@configuration、@Component、@ComponentScan,@Import、@ImportSource注解,如果不包含则再判断是否存在标注有@Bean方法,如果以上满足一项则添加进入一个待解析列表中:configCandidates。
  3. 如果待解析的类列表为空则直接返回不进行解析,否则将对这些类进行排序(是否标注有@Order注解)。
  4. 进行解析。
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		// 用来保存解析出来的bean定义,BeanDefinitionHolder是一个Bean定义的包装对象,里面主要包括了BeanDefinition,BeanName,Alias等信息
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();

		// 获取bean定义注册中心中的所有bean的名称.
		String[] candidateNames = registry.getBeanDefinitionNames();

		// 遍历所有的BeanDefinition的名称,筛选出带有注解的BeanDefinition
		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);
				}
			}
			// 校验当前的bean定义是否为一个候选的配置类,检查逻辑是判断类上是否标注了@Configuration注解或者是否存在标注了@Bean的方法
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
			}
		}

		// 判断扫描到的配置类List是否为空,如果为空,表示没有配置类,直接返回.
		if (configCandidates.isEmpty()) {
			return;
		}

		// Sort by previously determined @Order value, if applicable
		// 对配置类进行排序,配置类的顺序可以通过配置类上的@Order注解来进行指定.
		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;
		// DefaultListableBeanFactory实现了SingletonBeanFactory接口.
		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();
		}

		// 初始化配置类的解析器,用来解析使用@Configuration标注的配置类.
		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 {
			// 解析配置类中的注解信息,例如:ComponentScan[s], PropertySource[s], ImportResource
			parser.parse(candidates);

			// 做一些配置类的基本校验
			// 	 例如:(1) 标注@Configuration的类不能是final类型的; (2)标注@Bean的方法是否为静态的等等。。。
			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());
			}

			// 加载配置类中的bean定义,包括执行BeanDefinitionRegistrar接口的registryBeanDefinitions方法给容器中注册自定义的组件.
			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();
		}
	}

        我们来看下checkConfigurationClassCandidate方法来看下他是如何判断类是否是一个解析类。

	public static boolean checkConfigurationClassCandidate(
			BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {

		String className = beanDef.getBeanClassName();
		// 如果bean定义对应的class为null || bean定义中存在着工厂方法
		if (className == null || beanDef.getFactoryMethodName() != null) {
			return false;
		}

		//   注意:Spring内部的BeanDefinition默认都是RootBeanDefinition,这个类继承了AbstractBeanDefinition
		AnnotationMetadata metadata;
		// 	通过注解扫描得到的BeanDefinition都属于AnnotatedGenericBeanDefinition,实现了AnnotatedBeanDefinition接口.
		// 此处判断当前的BeanDefinition是否属于AnnotatedBeanDefinition。
		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.
			// 注意:此处的处理逻辑和5.2的Spring不同.
			Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
			metadata = new StandardAnnotationMetadata(beanClass, true);
		}
		else {
			try {
				MetadataReader metadataReader = metadataReaderFactory.getMetadataReader(className);
				metadata = metadataReader.getAnnotationMetadata();
			}
			catch (IOException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Could not find class file for introspecting configuration annotations: " +
							className, ex);
				}
				return false;
			}
		}
		// 当前的bean定义是否为一个配置类。即:是否标注有@Configuration注解
		if (isFullConfigurationCandidate(metadata)) {
			beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
		}
		// lite: 类似,标注有@Component,@ComponentScan,@Import,@ImportSource的类就满足isLiteConfiguration的条件.
		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.
		// 获取排序优先级信息
		Integer order = getOrder(metadata);
		if (order != null) {
			// 设置bean定义的优先级
			beanDef.setAttribute(ORDER_ATTRIBUTE, order);
		}
		return true;
	}

        前面判断BeanDefiniton主要是想获取BeanDefinition的元数据信息,然后判断是否标注有@Configuration注解,如果没有,则标判断是否注有@Component,@ComponentScan,@Import,@ImportSource的类就满足isLiteConfiguration的条件。我们来看下他是如何判断的:

	public static boolean isLiteConfigurationCandidate(AnnotationMetadata metadata) {
		// Do not consider an interface or an annotation...
		// 如果当前的bean定义指定的class是否为一个接口.
		if (metadata.isInterface()) {
			return false;
		}

		// 如果带有:@Component @ComponentScan @Import @ImportResource注解,则表示是一种类似于配置类的候选配置
		//     lite: 类似
		for (String indicator : candidateIndicators) {
			if (metadata.isAnnotated(indicator)) {
				return true;
			}
		}
		try {
			// 查看当前的bean定义中是否包括标注有@Bean注解的方法.
			return metadata.hasAnnotatedMethods(Bean.class.getName());
		}
		catch (Throwable ex) {
			if (logger.isDebugEnabled()) {
				logger.debug("Failed to introspect @Bean methods on class [" + metadata.getClassName() + "]: " + ex);
			}
			return false;
		}


	static {
		candidateIndicators.add(Component.class.getName());
		candidateIndicators.add(ComponentScan.class.getName());
		candidateIndicators.add(Import.class.getName());
		candidateIndicators.add(ImportResource.class.getName());
	}

          这个类,一开始就初始化了四个注解:@Component,@ComponentScan,@Import,@ImportSource,如果都没有包含则回去判断是否有标注有@Bean的方法。

        以上条件满足则就是需要进行解析的配置类,接下来就是真正的解析工作:

	public void parse(Set<BeanDefinitionHolder> configCandidates) {
		for (BeanDefinitionHolder holder : configCandidates) {
			BeanDefinition bd = holder.getBeanDefinition();
			try {
				// 配置类的Bean定义类型为AnnotationGenericBeanDefinition,实现自AnnotatedBeanDefinition接口.
				if (bd instanceof AnnotatedBeanDefinition) {
					parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
				}
				else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
					parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
				}
				else {
					parse(bd.getBeanClassName(), holder.getBeanName());
				}
			}
			catch (BeanDefinitionStoreException ex) {
				throw ex;
			}
			catch (Throwable ex) {
				throw new BeanDefinitionStoreException(
						"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
			}
		}
		// 处理延迟ImportSelector
		this.deferredImportSelectorHandler.process();
	}

	protected final void parse(Class<?> clazz, String beanName) throws IOException {
		processConfigurationClass(new ConfigurationClass(clazz, beanName));
	}

	protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
		// 处理配置类.
		processConfigurationClass(new ConfigurationClass(metadata, beanName));
	}

        上面就比较简单了,就是循环列表,然后判断BeanDefinition属于配置类的Bean定义类型为AnnotationGenericBeanDefinition,实现自AnnotatedBeanDefinition接口.但是其实他们都是调同样的解析方法processConfigurationClass,接下来看下这个方法的源码实现:

        我们也是来先说下这个源码主要做了哪些事情,然后在去看对应的源码实现:

  1. 首先判断是否需要跳过配置类的处理,主要是@Conditional注解的递归解析与判断。
  2. 判断是否重复处理,如果同一个配置类被处理两次,两次都属于被import的则合并导入类,返回,如果配置类不是被导入的,则移除旧的使用新的配置类。
  3. 判断是否存在父类,递归调用asSourceClass方法来解析当前配置类及父配置类中的元数据信息,包括配置类上面的注解信息。
  4. 解析具体的配置类。
	protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
		// 判断是否需要跳过配置类的处理,主要是@Conditional注解的递归解析与判断.
		if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
			return;
		}

		// 第一次进入的时候,configurationClasses的size为0,existingClass也是null,在这里处理的是configuration重复的import
		// 如果同一个配置类被处理两次,两次都属于被import的则合并导入类,返回,如果配置类不是被导入的,则移除旧的使用新的配置类
		ConfigurationClass existingClass = this.configurationClasses.get(configClass);
		if (existingClass != null) {
			if (configClass.isImported()) {
				if (existingClass.isImported()) {
					existingClass.mergeImportedBy(configClass);
				}
				// Otherwise ignore new imported config class; existing non-imported class overrides it.
				return;
			}
			else {
				// Explicit bean definition found, probably replacing an import.
				// Let's remove the old one and go with the new one.
				this.configurationClasses.remove(configClass);
				this.knownSuperclasses.values().removeIf(configClass::equals);
			}
		}

		// Recursively process the configuration class and its superclass hierarchy
		// 递归调用asSourceClass方法来解析当前配置类及父配置类中的元数据信息,包括配置类上面的注解信息
		// 处理配置类,由于配置类可能存在父类(若父类的全类名是以jva开头的,则除外),所有的需要将configclass变成sourceClass去解析,然后返回sourceClass的父类
		// 如果此时父类为空,则不会进行while循环去解析,如果父类不为空,则会循环的去解析父类
		// SourceClass的意义:简单的包装类,目的是为了以统一的方式去处理带有注解的类,不管这些类是如何加载的
		// 如果无法理解,可以把它当成一个黑盒,不会影响看Spring源码的主流程。
		SourceClass sourceClass = asSourceClass(configClass);
		do {
			// 解析具体的配置类.
			sourceClass = doProcessConfigurationClass(configClass, sourceClass);
		}
		while (sourceClass != null);

		this.configurationClasses.put(configClass, configClass);
	}

        看到doProcessConfigurationClass大家肯定就知道了,这里就是真正解析配置文件的地方,我们来看下这个源码做了哪些事情:

  1. 判断是否是标注@Component注解,处理@Component注解和@Configuration注解。@Configuration注解上也标注的是@Component,被@Configuration标注的配置类本身也是一个bean组件,然后去处理我们的内部类,Spring是支持内部类标注配置类的,然后内部类之中又是可以继续标注,所以这里面有一个递归解析内部类。
  2. 然后处理@PropertySource注解。
  3. 处理@ComponentScan注解或者@ComponentScans注解,并将扫描包下的所有bean转换成填充之后的ConfigurationClass,因为扫描到的类可能也添加了@ComponentScan和@ComponentScans注解,因此需要循环递归解析。
  4. 处理@Import注解。其中会调用子类中的selectImports方法,获取导入的Bean组件的名称.
  5. 处理@ImportResource注解。
  6. 处理配置类中标注有@Bean注解的方法.
  7. 处理接口的默认实现方法,jdk8之后,接口中的方法也可以有默认实现。所以默认接口中默认实现的方法上也可能标注有@Bean注解。
protected final SourceClass  doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
			throws IOException {

		// 处理@Component注解和@Configuration注解。@Configuration注解上也标注的是@Component,被@Configuration标注的配置类本身也是一个bean组件
		if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
			// Recursively process any member (nested) classes first
			// 处理内部类,类似如下
			/**
			 * @Component
			 * @Configuration
			 * class ClassA {
			 * 		@Component
			 * 		@Configuration
			 * 		@ComponentScan({""})
			 *		class ClassB {
			 *
			 *		}
			 * }
			 */
			processMemberClasses(configClass, sourceClass);
		}

		// 处理@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");
			}
		}

		// 处理@ComponentScan注解或者@ComponentScans注解,并将扫描包下的所有bean转换成填充之后的ConfigurationClass
		// 此处就是将自定义的bean加载到IOC容器,因为扫描到的类可能也添加了@ComponentScan和@ComponentScans注解,因此需要循环递归解析
		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和@ComponentScans配置的扫描包所包含的类。例如:basePackages="com.wb.spring"。则会在该步
				//  骤中扫描出这个包及子包下的class,然后将其解析为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
				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
					BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
					if (bdCand == null) {
						bdCand = holder.getBeanDefinition();
					}
					// 判断当前的bean定义是否为一个配置类,如果是配置类,继续递归解析
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
						// 递归调用parse方法,继续解析。
						parse(bdCand.getBeanClassName(), holder.getBeanName());
					}
				}
			}
		}

		// 处理@Import注解。其中会调用子类中的selectImports方法,获取导入的Bean组件的名称.
		processImports(configClass, sourceClass, getImports(sourceClass), true);

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

		// 处理配置类中标注有@Bean注解的方法.
		Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
		for (MethodMetadata methodMetadata : beanMethods) {
			configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
		}

		// Process default methods on interfaces
		// 处理接口的默认实现方法,jdk8之后,接口中的方法也可以有默认实现。所以默认接口中默认实现的方法上也可能标注有@Bean注解
		processInterfaces(configClass, sourceClass);

		// Process superclass, if any
		if (sourceClass.getMetadata().hasSuperClass()) {
			String superclass = sourceClass.getMetadata().getSuperClassName(); // 获取配置类的父类class名称
			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;
	}

       我们接下来看看Spring各个方法中是如何解析的,首先我们先来看下是如何解析内部类的。

 

	private void processMemberClasses(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
		// 获取标注有@Component注解的类对应的内部,然后去处理内部类上标注的注解
		Collection<SourceClass> memberClasses = sourceClass.getMemberClasses();
		if (!memberClasses.isEmpty()) {
			List<SourceClass> candidates = new ArrayList<>(memberClasses.size());
			for (SourceClass memberClass : memberClasses) {
				if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
						!memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
					candidates.add(memberClass);
				}
			}
			// 对内部类进行排序,因为一个配置类中可能包含有其他的多个配置类,而且这些配置类中可能还标注着@Order注解,指定了执行顺序
			OrderComparator.sort(candidates);
			for (SourceClass candidate : candidates) {
				// 判断栈中是否包含需要处理的configClass,如果包含,说明了存在着循环引入
				if (this.importStack.contains(configClass)) {
					this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
				}
				else {
					// 先压栈,将最外层的配置类压栈处理
					this.importStack.push(configClass);
					try {
						// 递归处理当前已经压入栈的配置类
						processConfigurationClass(candidate.asConfigClass(configClass));
					}
					finally {
						// 每处理完一个内部类,就将内部类执行出栈操作。最后出栈的是最外层的配置类
						this.importStack.pop();
					}
				}
			}
		}
	}

        也是循环去判断内部类是否需要解析,具体判断逻辑也是跟上面判断是否需要解析的逻辑一样,如果需要解析,那么就对这些内部类进行递归解析。

        接下来我们来看是如何解析:处理@PropertySource注解。

	private void processPropertySource(AnnotationAttributes propertySource) throws IOException {

		// 解析:@PropertySource(value = {"classpath:public.properties"},encoding = "UTF-8", name = "testSource", ignoreResourceNotFound = false)

		String name = propertySource.getString("name");
		if (!StringUtils.hasLength(name)) {
			name = null;
		}

		// 资源文件的字符编码
		String encoding = propertySource.getString("encoding");
		if (!StringUtils.hasLength(encoding)) {
			encoding = null;
		}
		String[] locations = propertySource.getStringArray("value");
		Assert.isTrue(locations.length > 0, "At least one @PropertySource(value) location is required");

		// 如果未找到对应的资源,是否忽略,默认值为false。表示不忽略,没找到资源,将会抛出异常
		boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

		// 获取自定义的属性资源工厂类,用于创建属性资源对象来解析属性资源配置文件的内容,未指定,则使用默认的DefaultPropertySourceFactory
		Class<? extends PropertySourceFactory> factoryClass = propertySource.getClass("factory");
		PropertySourceFactory factory = (factoryClass == PropertySourceFactory.class ?
				DEFAULT_PROPERTY_SOURCE_FACTORY : BeanUtils.instantiateClass(factoryClass));

		for (String location : locations) {
			try {
				// 解析资源文件的真实文件路径,包括占位符的解析替换操作
				String resolvedLocation = this.environment.resolveRequiredPlaceholders(location);

				// 根据解析到的真实资源文件路径,将资源文件内容转换为Resource资源对象
				Resource resource = this.resourceLoader.getResource(resolvedLocation);

				// 将解析到的资源对象放到资源对象集合中
				addPropertySource(factory.createPropertySource(name, new EncodedResource(resource, encoding)));
			}
			catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) {
				// Placeholders not resolvable or resource not found when trying to open it
				// 如果忽略未找到资源的情况下,则只会打印出日志信息。如果不忽略,将会抛出异常
				if (ignoreResourceNotFound) {
					if (logger.isInfoEnabled()) {
						logger.info("Properties location [" + location + "] not resolvable: " + ex.getMessage());
					}
				}
				else {
					throw ex;
				}
			}
		}
	}

	private void addPropertySource(PropertySource<?> propertySource) {
		String name = propertySource.getName();
		MutablePropertySources propertySources = ((ConfigurableEnvironment) this.environment).getPropertySources();

		if (this.propertySourceNames.contains(name)) {
			// We've already added a version, we need to extend it
			PropertySource<?> existing = propertySources.get(name);
			if (existing != null) {
				PropertySource<?> newSource = (propertySource instanceof ResourcePropertySource ?
						((ResourcePropertySource) propertySource).withResourceName() : propertySource);
				if (existing instanceof CompositePropertySource) {
					((CompositePropertySource) existing).addFirstPropertySource(newSource);
				}
				else {
					if (existing instanceof ResourcePropertySource) {
						existing = ((ResourcePropertySource) existing).withResourceName();
					}
					CompositePropertySource composite = new CompositePropertySource(name);
					composite.addPropertySource(newSource);
					composite.addPropertySource(existing);
					propertySources.replace(name, composite);
				}
				return;
			}
		}

		if (this.propertySourceNames.isEmpty()) {
			propertySources.addLast(propertySource);
		}
		else {
			String firstProcessed = this.propertySourceNames.get(this.propertySourceNames.size() - 1);
			propertySources.addBefore(firstProcessed, propertySource);
		}
		this.propertySourceNames.add(name);
	}

        就是将解析到的配置文件放到MutablePropertySources中,如果大家有印象我们在初始化Bean容器的时候也解析有两个默认的配置文件,大家可以去看一下,这里就不展开了。

        接下来看如何解析@ComponentScan注解或者@ComponentScans注解。

	public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
		// 创建扫描器对象
		ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
				componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

		// 获取@ComponentScan中指定的bean名称生成器
		Class<? extends BeanNameGenerator> generatorClass = componentScan.getClass("nameGenerator");
		boolean useInheritedGenerator = (BeanNameGenerator.class == generatorClass);
		scanner.setBeanNameGenerator(useInheritedGenerator ? this.beanNameGenerator :
				BeanUtils.instantiateClass(generatorClass));

		// 获取scopedProxy属性
		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));
		}

		// 获取resourcePattern属性
		scanner.setResourcePattern(componentScan.getString("resourcePattern"));

		// 获取@ComponentScan中指定的需要包含的bean定义过滤器集合。用来指定包扫描时需要包含的Component
		for (AnnotationAttributes filter : componentScan.getAnnotationArray("includeFilters")) {
			for (TypeFilter typeFilter : typeFiltersFor(filter)) {
				scanner.addIncludeFilter(typeFilter);
			}
		}
		// 获取excludeFilter集合,用来指定bean定义解析过程中需要排除的Component
		for (AnnotationAttributes filter : componentScan.getAnnotationArray("excludeFilters")) {
			for (TypeFilter typeFilter : typeFiltersFor(filter)) {
				scanner.addExcludeFilter(typeFilter);
			}
		}
		// 获取lazyInit属性
		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);
			}
		});
		// 通过ClasspathBeanDefinitionScanner对象执行扫描操作
		return scanner.doScan(StringUtils.toStringArray(basePackages));
	}


	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) {
			// 从类路径下扫描候选的bean定义
			Set<BeanDefinition> candidates = findCandidateComponents(basePackage);
			for (BeanDefinition candidate : candidates) {
				// 解析@Scope注解,包括scopeName和proxyMode属性
				ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(candidate);
				candidate.setScope(scopeMetadata.getScopeName());
				// 通过名称生成器来生成beanName
				String beanName = this.beanNameGenerator.generateBeanName(candidate, this.registry);
				if (candidate instanceof AbstractBeanDefinition) {
					// 设置当前的bean是否可以自动装配到其他的bean中,即:autoWireCandidate属性
					postProcessBeanDefinition((AbstractBeanDefinition) candidate, beanName);
				}
				if (candidate instanceof AnnotatedBeanDefinition) {
					// 处理通用注解。例如:@Lazy,@Primary,@Role,@DependsOn,@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);
					// 注册bean定义到bean注册中心.
					registerBeanDefinition(definitionHolder, this.registry);
				}
			}
		}
		return beanDefinitions;
	}

	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*: + com/wb/spring/propertyvalue/**/*.class
			// resourcePattern默认为:**/*.class
			String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
					resolveBasePackage(basePackage) + '/' + this.resourcePattern;
			/**
			 * 根据入参的类路径去匹配该路径下的所有class,并转换为Resource对象数组
			 * 默认的实现类为:PathMatchingResourcePatternResolver
			 */
			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);
						// 判断是否是excludeFilter中需要排除的bean定义或者是否是includeFilter中需要包含的bean定义.
						if (isCandidateComponent(metadataReader)) {
							// 根据读取到的配置类上面的元注解信息创建bean定义.
							ScannedGenericBeanDefinition sbd = new ScannedGenericBeanDefinition(metadataReader);
							// 设置bean定义的资源路径,即:class的全路径
							sbd.setResource(resource);
							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;
	}

	protected boolean isCandidateComponent(MetadataReader metadataReader) throws IOException {
		// 遍历所有的excludeFilter,如果是需要排除的bean定义,直接返回false
		for (TypeFilter tf : this.excludeFilters) {
			if (tf.match(metadataReader, getMetadataReaderFactory())) {
				return false;
			}
		}

		/**
		* 遍历所有的includeFilter,如果是需要包含的bean定义,则再去根据bean定义对应的元数据信息判断
		 * 是否标注有@Conditional注解,以及@Conditional注解是否排除了该bean定义
		 */
		for (TypeFilter tf : this.includeFilters) {
			if (tf.match(metadataReader, getMetadataReaderFactory())) {
				return isConditionMatch(metadataReader);
			}
		}
		return false;
	}



        流程也比较的简单,就是创建扫描器对象,先去获取注解上标注的属性,然后将对应的路径的.class文件进行扫描然后判断是否满足条件,如果满足条件则加入集合中。

        @ImportResource注解这里我们不展开了,因为用的不多。我们来看下他是如何处理配置类中标注有@Bean注解的方法。

	private Set<MethodMetadata> retrieveBeanMethodMetadata(SourceClass sourceClass) {
		// sourceClass: 具体的配置类
		AnnotationMetadata original = sourceClass.getMetadata();
		// original的默认类型为AnnotationMetadataReadingVisitor
		Set<MethodMetadata> beanMethods = original.getAnnotatedMethods(Bean.class.getName());
		if (beanMethods.size() > 1 && original instanceof StandardAnnotationMetadata) {
			// Try reading the class file via ASM for deterministic declaration order...
			// Unfortunately, the JVM's standard reflection returns methods in arbitrary
			// order, even between different runs of the same application on the same JVM.
			try {
				AnnotationMetadata asm =
						this.metadataReaderFactory.getMetadataReader(original.getClassName()).getAnnotationMetadata();
				Set<MethodMetadata> asmMethods = asm.getAnnotatedMethods(Bean.class.getName());
				if (asmMethods.size() >= beanMethods.size()) {
					Set<MethodMetadata> selectedMethods = new LinkedHashSet<>(asmMethods.size());
					for (MethodMetadata asmMethod : asmMethods) {
						for (MethodMetadata beanMethod : beanMethods) {
							if (beanMethod.getMethodName().equals(asmMethod.getMethodName())) {
								selectedMethods.add(beanMethod);
								break;
							}
						}
					}
					if (selectedMethods.size() == beanMethods.size()) {
						// All reflection-detected methods found in ASM method set -> proceed
						beanMethods = selectedMethods;
					}
				}
			}
			catch (IOException ex) {
				logger.debug("Failed to read class file via ASM for determining @Bean method order", ex);
				// No worries, let's continue with the reflection metadata we started with...
			}
		}
		return beanMethods;
	}

        好了到这里ConfigurationClassPostProcessor这个配置类我们就分析到这里了,到这里我们其实可以感觉Spring是一个拓展性极强的框架,这个类3.0版本才注入,但是对应Spring原有架构并没有太多变动。

        我这里上传一个我自己画的大概的流程图,可以看下然后回忆一下上面源码将的流程对应上。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值