目录

  • invokeBeanFactoryPostProcessors
  • PostProcessorRegistrationDelegate
  • CachingMetadataReaderFactoryPostProcessor
  • ConfigurationWarningsPostProcessor
  • getBeanNamesForType
  • ConfigurationClassPostProcessor
  • ConfigurationClassParser.parse()
  • doProcessConfigurationClass 处理ConfigurationClass
  • processMemberClasses 获取配置类的嵌套内部类
  • componentScanParser.parse 解析componentScan注解
  • processImports
  • deferredImportSelectorHandler.process()导入选择器的处理器
  • ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(configClasses)
  • ConfigurationClassParser.DeferredImportSelectorHandler 导入包处理
  • AutoConfigurationImportSelector
  • ConfigurationClassParser.DeferredImportSelectorGroupingHandler
  • AutoConfigurationImportSelector.AutoConfigurationGroup
  • ConfigurationClassParser.DeferredImportSelectorGrouping
  • ConfigurationClassParser.processImports
  • PropertySourcesPlaceholderConfigurer
  • BeanFactoryPostProcessor层级
  • BeanDefinitionRegistryPostProcessor


在执行refreshContext刷新上下文的过程中,首次执行了对BeanFactoryPostProcessor后置处理器的执行,此时BeanFactory容器中有两个bean工厂后置处理器:

ConfigurationWarningsApplicationContextInitializer.ConfigurationWarningsPostProcessor

SharedMetadataReaderFactoryContextInitializer.CachingMetadataReaderFactoryPostProcessor,

接下来我们看执行BeanFactoryPostProcessor的入口:invokeBeanFactoryPostProcessors

invokeBeanFactoryPostProcessors

方法内部首先调用了PostProcessorRegistrationDelegate后置处理器注册委派者的invokeBeanFactoryPostProcessors方法

public abstract class AbstractApplicationContext extends DefaultResourceLoader
		implements ConfigurableApplicationContext {
	//实例化并调用所有已注册的BeanFactoryPostProcessor bean,如果给出显式顺序,则遵循此顺序。
	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 (!NativeDetector.inNativeImage() && beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
			beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
			beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
		}
	}

}

PostProcessorRegistrationDelegate

后置处理器注册委派者主要是根据首要类及其上面的配置,对config class进行解析,同时根据Configuration class加载BeanDefinition;同时注册了属性占位符后置处理器、Aop代理后置处理器

final class PostProcessorRegistrationDelegate {

	/**
	*警告:虽然看起来这个方法的主体可以很容易地重构以避免使用多个循环和多个列表,
	*但使用多个列表和多次传递处理器名称是有意为之的。我们必须确保我们尊重优先订购和订购处理器的合同。
	*特别地,我们不能让处理器以错误的顺序被实例化(通过getBean()调用)或在ApplicationContext中注册。
	*
	*
	*/
	public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
		//定义一个处理过的bean集合
		Set<String> processedBeans = new HashSet<>();
		//如果beanFactory 是一个BeanDefinition注册器
		if (beanFactory instanceof BeanDefinitionRegistry) {
			BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
			//定义一个常规的后置处理器集合
			List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
			//定义一个 Bean定义注册表后处理集合
			List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

			for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
				//判断postProcessor 是否是BeanDefinitionRegistryPostProcessor类型,然后强转成BeanDefinitionRegistryPostProcessor ,
				//调用registryProcessor的postProcessBeanDefinitionRegistry方法,首先调用的是CachingMetadataReaderFactoryPostProcessor的方法,接下来调用ConfigurationWarningsPostProcessor的方法
				if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
					BeanDefinitionRegistryPostProcessor registryProcessor =
							(BeanDefinitionRegistryPostProcessor) postProcessor;
					//执行完postProcessBeanDefinitionRegistry方法,将执行完的后置处理器添加到registryProcessors集合中
					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.
			//不要在这里初始化FactoryBeans:我们需要让所有常规bean保持未初始化状态,
			//以便bean工厂后处理程序应用于它们!
			List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

			// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
			//首先,调用实现优先排序的BeanDefinitionRegistryPostProcessors,postProcessorNames  = org.springframework.context.annotation.internalConfigurationAnnotationProcessor,class = ConfigurationClassPostProcessor
			//根据类型获取BeanDefinitionMap中的postProcessorNames internalConfigurationAnnotationProcessor
			//,此时符合条件的只有internalConfigurationAnnotationProcessor
			String[] postProcessorNames =
					beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
					//将当前bean加入到集合中,得到ConfigurationClassPostProcessor
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					processedBeans.add(ppName);
				}
			}
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			registryProcessors.addAll(currentRegistryProcessors);
			//此方法调用获取到的BeanDefinitionRegistryPostProcessors 类型的对象进行处理
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				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, beanFactory.getApplicationStartup());
			currentRegistryProcessors.clear();

			// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
			//最后,调用所有其他BeanDefinitionRegistryPostProcessors,直到不再出现其他的
			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, beanFactory.getApplicationStartup());
				currentRegistryProcessors.clear();
			}

			// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
			invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
			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!
		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.
                //priorityOrderedPostProcessors = [propertySourcesPlaceholderConfigurer],此处通过调用属性源占位符配置器的postProcessBeanFactory方法,添加了属性源调用者,通过key获取value
		sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

		// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
		// [DependsOnDatabaseInitializationPostProcessor]
		List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
		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<>(nonOrderedPostProcessorNames.size());
		for (String postProcessorName : nonOrderedPostProcessorNames) {
			nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
		}
		invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);
		//0 = {EventListenerMethodProcessor@6521} 
		//1 = {ErrorMvcAutoConfiguration$PreserveErrorControllerTargetClassPostProcessor@6522} 
		//2 = {AopAutoConfiguration$ClassProxyingConfiguration$lambda@6523} 
		// Clear cached merged bean definitions since the post-processors might have
		// modified the original metadata, e.g. replacing placeholders in values...
		beanFactory.clearMetadataCache();
	}
	
	//循环获取并进行调用,此处第一次调用
	private static void invokeBeanDefinitionRegistryPostProcessors(
			Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry, ApplicationStartup applicationStartup) {

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

}

CachingMetadataReaderFactoryPostProcessor

调用CachingMetadataReaderFactoryPostProcessor的postProcessBeanDefinitionRegistry,方法内部调用register方法;
具体来说,CachingMetadataReaderFactoryPostProcessor注册了一个internalCachingMetadataReaderFactory类型的beanDefinition,
同时给internalConfigurationAnnotationProcessor的BeanDefinition的pv添加了一个key为metadataReaderFactory,value = RuntimeBeanReference,name=internalCachingMetadataReaderFactory的属性值

class SharedMetadataReaderFactoryContextInitializer
		implements ApplicationContextInitializer<ConfigurableApplicationContext>, Ordered {
	public static final String BEAN_NAME = "org.springframework.boot.autoconfigure."
			+ "internalCachingMetadataReaderFactory";
	static class CachingMetadataReaderFactoryPostProcessor
			implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {

		@Override
		public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
			//注册bean
			register(registry);
			//配置后处理
			configureConfigurationClassPostProcessor(registry);
		}

		private void register(BeanDefinitionRegistry registry) {
			//此方法生成了一个普通BeanDefinition,并设置了BeanDefinition中class= SharedMetadataReaderFactoryBean,supplier = SharedMetadataReaderFactoryBean::new
			BeanDefinition definition = BeanDefinitionBuilder
					.genericBeanDefinition(SharedMetadataReaderFactoryBean.class, SharedMetadataReaderFactoryBean::new)
					.getBeanDefinition();
			//将生成的beanDefinition注册到了容器中
			registry.registerBeanDefinition(BEAN_NAME, definition);
		}

		private void configureConfigurationClassPostProcessor(BeanDefinitionRegistry registry) {
			try {
				configureConfigurationClassPostProcessor(
						registry.getBeanDefinition(AnnotationConfigUtils.CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
			}
			catch (NoSuchBeanDefinitionException ex) {
			}
		}
		//此时的definition 的beabClass=org.springframework.context.annotation.ConfigurationClassPostProcessor
		private void configureConfigurationClassPostProcessor(BeanDefinition definition) {
			if (definition instanceof AbstractBeanDefinition) {
				configureConfigurationClassPostProcessor((AbstractBeanDefinition) definition);
				return;
			}
			configureConfigurationClassPostProcessor(definition.getPropertyValues());
		}


		private void configureConfigurationClassPostProcessor(AbstractBeanDefinition definition) {
			//首先获取回调函数instanceSupplier ,此时instanceSupplier = null;否则根据提供的函数生成一个
			//ConfigurationClassPostProcessorCustomizingSupplier对象
			Supplier<?> instanceSupplier = definition.getInstanceSupplier();
			if (instanceSupplier != null) {
				definition.setInstanceSupplier(
						new ConfigurationClassPostProcessorCustomizingSupplier(this.context, instanceSupplier));
				return;
			}
			configureConfigurationClassPostProcessor(definition.getPropertyValues());
		}
		private void configureConfigurationClassPostProcessor(MutablePropertyValues propertyValues) {
			//此时的propertyValues为空,添加了一个运行时Bean引用 = internalCachingMetadataReaderFactory
			propertyValues.add("metadataReaderFactory", new RuntimeBeanReference(BEAN_NAME));
		}
	}

}

internalConfigurationAnnotationProcessor beanDefinition是何时注册的?

  • AnnotationConfigUtils
public abstract class AnnotationConfigUtils {
	//内部托管的Configuration注释处理器的bean名。
	public static final String CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME =
			"org.springframework.context.annotation.internalConfigurationAnnotationProcessor";
}

ConfigurationWarningsPostProcessor

此方法根据注解类来解析包路径,如果没有提供包路径,则根据注解类生成默认扫描包路径。同时对包路径进行错误性检查 以org 、org.springframework开头

public class ConfigurationWarningsApplicationContextInitializer
		implements ApplicationContextInitializer<ConfigurableApplicationContext> {
	protected static final class ConfigurationWarningsPostProcessor
			implements PriorityOrdered, BeanDefinitionRegistryPostProcessor {
		public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
			//对checks进行校验,此时checks.length = 1,checks[0]=ComponentScanPackageCheck
			for (Check check : this.checks) {
				String message = check.getWarning(registry);
				if (StringUtils.hasLength(message)) {
					warn(message);
				}
			}

		}

	}

	//检查问题包上的@ComponentScan。
        // 启动类上不允许包路径配置为  org 、org.springframework开头
	protected static class ComponentScanPackageCheck implements Check {

		private static final Set<String> PROBLEM_PACKAGES;
		static {
			Set<String> packages = new HashSet<>();
			packages.add("org.springframework");
			packages.add("org");
			PROBLEM_PACKAGES = Collections.unmodifiableSet(packages);
		}

		static {
			Set<String> packages = new HashSet<>();
			packages.add("org.springframework");
			packages.add("org");
			PROBLEM_PACKAGES = Collections.unmodifiableSet(packages);
		}

		@Override
		public String getWarning(BeanDefinitionRegistry registry) {
			Set<String> scannedPackages = getComponentScanningPackages(registry);
			//拿到包路径之后,获取有问题的包路径
			List<String> problematicPackages = getProblematicPackages(scannedPackages);
			if (problematicPackages.isEmpty()) {
				return null;
			}
			return "Your ApplicationContext is unlikely to start due to a @ComponentScan of "
					+ StringUtils.collectionToDelimitedString(problematicPackages, ", ") + ".";
		}

		protected Set<String> getComponentScanningPackages(BeanDefinitionRegistry registry) {
			Set<String> packages = new LinkedHashSet<>();
			//此时names = 
			//0 = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
			//1 = "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"
			//2 = "org.springframework.context.annotation.internalCommonAnnotationProcessor"
			//3 = "org.springframework.context.event.internalEventListenerProcessor"
			//4 = "org.springframework.context.event.internalEventListenerFactory"
			//5 = "userProviderBootstrap"
			//6 = "org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory"
			String[] names = registry.getBeanDefinitionNames();
			for (String name : names) {
				//循环对BeanDefinition进行判断,如果是注解型BeanDefinition,则进行处理,此时满足条件的BeanDefinition为userProviderBootstrap
				BeanDefinition definition = registry.getBeanDefinition(name);
				if (definition instanceof AnnotatedBeanDefinition) {
					AnnotatedBeanDefinition annotatedDefinition = (AnnotatedBeanDefinition) definition;
					//根据扫描到的注解beanDefinition解析类上标注的扫描包
					addComponentScanningPackages(packages, annotatedDefinition.getMetadata());
				}
			}
			return packages;
		}

		//传入扫描包变量,根据注解元信息进行判断
		private void addComponentScanningPackages(Set<String> packages, AnnotationMetadata metadata) {
			//获取到注解上的所有属性 basePackageClasses、basePackages、excludeFilters、includeFilters
			//lazyInit、nameGenerator、resourcePattern、scopeResolver、scopedProxy、useDefaultFilters、value
			AnnotationAttributes attributes = AnnotationAttributes
					.fromMap(metadata.getAnnotationAttributes(ComponentScan.class.getName(), true));
			if (attributes != null) {
				addPackages(packages, attributes.getStringArray("value"));
				addPackages(packages, attributes.getStringArray("basePackages"));
				addClasses(packages, attributes.getStringArray("basePackageClasses"));
				if (packages.isEmpty()) {
					//此时packages为空,添加默认包路径com.bail.user.service
					packages.add(ClassUtils.getPackageName(metadata.getClassName()));
				}
			}
		}

		private boolean isProblematicPackage(String scannedPackage) {
			if (scannedPackage == null || scannedPackage.isEmpty()) {
				return true;
			}
			//默认的PROBLEM_PACKAGES有两个路径:org.springframework、org
			return PROBLEM_PACKAGES.contains(scannedPackage);
		}
	}
}

isProblematicPackage此处的方法命名和返回值有歧义

getBeanNamesForType

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory
		implements ConfigurableListableBeanFactory, BeanDefinitionRegistry, Serializable {
	//此处参数为BeanDefinitionRegistryPostProcessor.class ,true,false
	private String[] doGetBeanNamesForType(ResolvableType type, boolean includeNonSingletons, boolean allowEagerInit) {
		List<String> result = new ArrayList<>();

		// Check all bean definitions.
		for (String beanName : this.beanDefinitionNames) {
			// Only consider bean as eligible if the bean name is not defined as alias for some other bean.
			if (!isAlias(beanName)) {
				try {
					RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
					// Only check bean definition if it is complete.
					if (!mbd.isAbstract() && (allowEagerInit ||
							(mbd.hasBeanClass() || !mbd.isLazyInit() || isAllowEagerClassLoading()) &&
									!requiresEagerInitForType(mbd.getFactoryBeanName()))) {
						boolean isFactoryBean = isFactoryBean(beanName, mbd);
						BeanDefinitionHolder dbd = mbd.getDecoratedDefinition();
						boolean matchFound = false;
						boolean allowFactoryBeanInit = (allowEagerInit || containsSingleton(beanName));
						boolean isNonLazyDecorated = (dbd != null && !mbd.isLazyInit());
						if (!isFactoryBean) {
							if (includeNonSingletons || isSingleton(beanName, mbd, dbd)) {
								matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
							}
						}
						else {
							if (includeNonSingletons || isNonLazyDecorated ||
									(allowFactoryBeanInit && isSingleton(beanName, mbd, dbd))) {
								matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
							}
							if (!matchFound) {
								// In case of FactoryBean, try to match FactoryBean instance itself next.
								beanName = FACTORY_BEAN_PREFIX + beanName;
								matchFound = isTypeMatch(beanName, type, allowFactoryBeanInit);
							}
						}
						if (matchFound) {
							result.add(beanName);
						}
					}
				}
				catch (CannotLoadBeanClassException | BeanDefinitionStoreException ex) {
					if (allowEagerInit) {
						throw ex;
					}
					// Probably a placeholder: let's ignore it for type matching purposes.
					LogMessage message = (ex instanceof CannotLoadBeanClassException ?
							LogMessage.format("Ignoring bean class loading failure for bean '%s'", beanName) :
							LogMessage.format("Ignoring unresolvable metadata in bean definition '%s'", beanName));
					logger.trace(message, ex);
					// Register exception, in case the bean was accidentally unresolvable.
					onSuppressedException(ex);
				}
				catch (NoSuchBeanDefinitionException ex) {
					// Bean definition got removed while we were iterating -> ignore.
				}
			}
		}

		// Check manually registered singletons too.
		for (String beanName : this.manualSingletonNames) {
			try {
				// In case of FactoryBean, match object created by FactoryBean.
				if (isFactoryBean(beanName)) {
					if ((includeNonSingletons || isSingleton(beanName)) && isTypeMatch(beanName, type)) {
						result.add(beanName);
						// Match found for this bean: do not match FactoryBean itself anymore.
						continue;
					}
					// In case of FactoryBean, try to match FactoryBean itself next.
					beanName = FACTORY_BEAN_PREFIX + beanName;
				}
				// Match raw bean instance (might be raw FactoryBean).
				if (isTypeMatch(beanName, type)) {
					result.add(beanName);
				}
			}
			catch (NoSuchBeanDefinitionException ex) {
				// Shouldn't happen - probably a result of circular reference resolution...
				logger.trace(LogMessage.format(
						"Failed to check manually registered singleton with name '%s'", beanName), ex);
			}
		}

		return StringUtils.toStringArray(result);
	}


}

ConfigurationClassPostProcessor

processConfigBeanDefinitions方法中,已注册的beanDefinitions:

0 = "org.springframework.context.annotation.internalConfigurationAnnotationProcessor"
1 = "org.springframework.context.annotation.internalAutowiredAnnotationProcessor"
2 = "org.springframework.context.annotation.internalCommonAnnotationProcessor"
3 = "org.springframework.context.event.internalEventListenerProcessor"
4 = "org.springframework.context.event.internalEventListenerFactory"
5 = "userProviderBootstrap"
6 = "org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory"

经过parser.parse(candidates)方法的处理,将自动导入的类从SpringFactory加载到了ConfigurationClassParser 的ConfigurationClasses容器中。
随后调用ConfigurationClassBeanDefinitionReader 对ConfigurationClasses进行BeanDefinition加载

public class ConfigurationClassPostProcessor implements BeanDefinitionRegistryPostProcessor,
		PriorityOrdered, ResourceLoaderAware, ApplicationStartupAware, BeanClassLoaderAware, EnvironmentAware {
	private ConfigurationClassBeanDefinitionReader reader;
	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);
		}
		this.registriesPostProcessed.add(registryId);

		processConfigBeanDefinitions(registry);
	}
	//基于configuration类的注册表构建并验证配置模型。
	public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		//声明的配置候选项
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
		//从工厂中获取候选项名称
		String[] candidateNames = registry.getBeanDefinitionNames();
		//for循环执行完毕,符合配置候选类的BeanDefinition只有UserProviderBootstrap 一个
		for (String beanName : candidateNames) {
			//获得ConfigurationClassPostProcessor 的BeanDefinition,pv包含一个metadataReaderFactory
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
			//获取的对应的属性为空
			if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				//UserProviderBootstrap BeanDefinition符合条件,加入配置候选类集合
				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
		//检测通过外围应用程序上下文提供的任何自定义bean名称生成策略
		SingletonBeanRegistry sbr = null;
		//BeanFactory 符合SingletonBeanRegistry
		if (registry instanceof SingletonBeanRegistry) {
			sbr = (SingletonBeanRegistry) registry;
			if (!this.localBeanNameGeneratorSet) {

				//此处获取的generator 为空
				BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
						AnnotationConfigUtils.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集合去重
		Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
		Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
		do {
			StartupStep processConfig = this.applicationStartup.start("spring.context.config-classes.parse");
			//调用解析器进行解析
			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);
			//此处经过加载,BeanDefinitionMap中含有152个BeanDefinition
			alreadyParsed.addAll(configClasses);
			processConfig.tag("classCount", () -> String.valueOf(configClasses.size())).end();
			//至此,根据首要类加载的BeanDefinition解析完毕,包括自动装配类
			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
		//将ImportRegistry注册为一个bean,以便支持importtaware @Configuration类
		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();
		}
	}

	//准备在运行时服务bean请求的Configuration类,将它们替换为cglib增强的子类。
	@Override
	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		int factoryId = System.identityHashCode(beanFactory);
		if (this.factoriesPostProcessed.contains(factoryId)) {
			throw new IllegalStateException(
					"postProcessBeanFactory already called on this post-processor against " + beanFactory);
		}
		this.factoriesPostProcessed.add(factoryId);
		if (!this.registriesPostProcessed.contains(factoryId)) {
			// BeanDefinitionRegistryPostProcessor hook apparently not supported...
			// Simply call processConfigurationClasses lazily at this point then.
			processConfigBeanDefinitions((BeanDefinitionRegistry) beanFactory);
		}

		enhanceConfigurationClasses(beanFactory);
		//添加一个Bean类型的后置处理器 ImportAwareBeanPostProcessor
		beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
	}
}
  • ConfigurationClassUtils
abstract class ConfigurationClassUtils {
	public static final String CONFIGURATION_CLASS_FULL = "full";
	public static final String CONFIGURATION_CLASS_LITE = "lite";
	public static final String CONFIGURATION_CLASS_ATTRIBUTE =
			Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "configurationClass");
	private static final String ORDER_ATTRIBUTE =
			Conventions.getQualifiedAttributeName(ConfigurationClassPostProcessor.class, "order");
	private static final Log logger = LogFactory.getLog(ConfigurationClassUtils.class);
	//候选指标
	private static final Set<String> candidateIndicators = new HashSet<>(8);
	static {
		candidateIndicators.add(Component.class.getName());
		candidateIndicators.add(ComponentScan.class.getName());
		candidateIndicators.add(Import.class.getName());
		candidateIndicators.add(ImportResource.class.getName());
	}

	public static boolean checkConfigurationClassCandidate(
			BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
		//className  = org.springframework.context.annotation.ConfigurationClassPostProcessor
		String className = beanDef.getBeanClassName();
		if (className == null || beanDef.getFactoryMethodName() != null) {
			return false;
		}

		AnnotationMetadata metadata;
		if (beanDef instanceof AnnotatedBeanDefinition &&
				className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
			// Can reuse the pre-parsed metadata from the given BeanDefinition...
			//是否可以重用给定BeanDefinition中预解析的元数据
			//userProviderBootstrap BeanDefinition进入此处
			metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();
		}
		//ConfigurationClassPostProcessor符合else if 判断
		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.
			//ConfigurationClassPostProcessor 符合BeanFactoryPostProcessor,返回false
			Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
			if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass) ||
					BeanPostProcessor.class.isAssignableFrom(beanClass) ||
					AopInfrastructureBean.class.isAssignableFrom(beanClass) ||
					EventListenerFactory.class.isAssignableFrom(beanClass)) {
				return false;
			}
			//SharedMetadataReaderFactoryBean进入此处
			metadata = AnnotationMetadata.introspect(beanClass);
		}
		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;
			}
		}
		//userProviderBootstrap  得到的config = "proxyBeanMethods" -> {Boolean@5288} true;"value" -> ""
		//SharedMetadataReaderFactoryBean 得到config = null;
		Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
		if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
			//为当前userProviderBootstrap BeanDefinition设置属性:***.configurationClass
			beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
		}
		else if (config != null || isConfigurationCandidate(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) {
			beanDef.setAttribute(ORDER_ATTRIBUTE, order);
		}

		return true;
	}
}
ConfigurationClassParser.parse()

当ConfigurationClassParser对首要类UserProviderBootstrap解析完毕之后,主要做了以下工作:
1、获取当前类的内部类,并对内部类符合配置类定义的类添加到缓存容器并进行处理,主要是处理标注了@Component及其派生类的类
2、加载配置类上导入的外部属性资源@PropertySource
2、解析当前类上标注了@ComponentScan的资源,使用类路径加载器解析配置类,并循环调用当前方法进行配置类的解析
3、解析@Import注解导入的类,主要在当前容器中加入了注解器和在当前解析类ConfigurationClassParser 的容器中,添加了导入包处理器ImportHandler
4、解析由ImportResource引入的资源类
5、处理由@Bean注解注册的BeanDefinition,添加到了配置类中的BeanMethod缓存中
6、最后处理接口(默认实现方法)和父类中的一些方法
解析完的相关信息,存储在ConfigurationClass中,同时解析到的BeanDefinition存储到了Map中,
调用完ConfigurationClassParser的parse方法后,开始调用deferredImportSelectorHandler 的process方法

/**
*解析一个{@link Configuration}类定义,填充一组{@link ConfigurationClass}对象(解析单个Configuration类可能会
*导致任意数量的ConfigurationClass对象,因为一个Configuration类可能会使用{@link import}注释导入另一个Configuration类)。
*
*/
class ConfigurationClassParser {

	private final DeferredImportSelectorHandler deferredImportSelectorHandler = new DeferredImportSelectorHandler();
	public void parse(Set<BeanDefinitionHolder> configCandidates) {
		for (BeanDefinitionHolder holder : configCandidates) {
			BeanDefinition bd = holder.getBeanDefinition();
			try {
				if (bd instanceof AnnotatedBeanDefinition) {
					//userProviderBootstrap BeanDefinition进入此处
					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);
			}
		}

		this.deferredImportSelectorHandler.process();
	}

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

	//配置类集合
	private final Map<ConfigurationClass, ConfigurationClass> configurationClasses = new LinkedHashMap<>();

	protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
		if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
			return;
		}

		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.
		//递归地处理配置类及其超类层次结构,此处得到的sourceClass  = UserProviderBootstrap
		//因为配置类可能存在层级,因此该循环是针对配置类的父类进行的,但是配置类对象是不会变的

		SourceClass sourceClass = asSourceClass(configClass, filter);
		do {
			sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
		}
		while (sourceClass != null);

		this.configurationClasses.put(configClass, configClass);
	}
	//工厂方法从{@link ConfigurationClass}中获取{@link SourceClass}
	private SourceClass asSourceClass(ConfigurationClass configurationClass, Predicate<String> filter) throws IOException {
		AnnotationMetadata metadata = configurationClass.getMetadata();
		if (metadata instanceof StandardAnnotationMetadata) {
			return asSourceClass(((StandardAnnotationMetadata) metadata).getIntrospectedClass(), filter);
		}
		return asSourceClass(metadata.getClassName(), filter);
	}
	//工厂方法从{@link Class}中获取{@link SourceClass}。
	SourceClass asSourceClass(@Nullable Class<?> classType, Predicate<String> filter) throws IOException {
		if (classType == null || filter.test(classType.getName())) {
			return this.objectSourceClass;
		}
		try {
			// Sanity test that we can reflectively read annotations,
			// including Class attributes; if not -> fall back to ASM
			for (Annotation ann : classType.getDeclaredAnnotations()) {
				AnnotationUtils.validateAnnotation(ann);
			}
			return new SourceClass(classType);
		}
		catch (Throwable ex) {
			// Enforce ASM via class name resolution
			return asSourceClass(classType.getName(), filter);
		}
	}
}
doProcessConfigurationClass 处理ConfigurationClass
class ConfigurationClassParser {
	private final ComponentScanAnnotationParser componentScanParser;
	/*
	*configClass: userProviderBootstrap
	*sourceClass: UserProviderBootstrap
	*
	*/
	protected final SourceClass doProcessConfigurationClass(
			ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
			throws IOException {
		//判断UserProviderBootstrap类上有Component注解,进行解析,因为该配置类中被@Component注解的
		//bean可能也是配置类
		if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
			// Recursively process any member (nested) classes first
			processMemberClasses(configClass, sourceClass, filter);
		}

		// Process any @PropertySource annotations
		//解析@PropertySources注解,该注解的作用便是引入额外的properties,文件解析过后再将文件属性值
		//注入到environment中,如果有相同的则替换新的,在某个配置上配置的属性文件,在属性导入后,在其他配置上也可以使用
		//同时,@PropertySource 和 @ConfigurationProperties注解配合使用,可以将属性文件与一个java类绑定,将
		//属性文件中的变量值注入到该Java类的成员变量中。
		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
		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();
					}
					//通过ComponentScan扫描到的BeanDefinition,会经过parse方法进行解析,最终还会调到此方法内,直到标注ComponentScan的类解析完毕
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
						parse(bdCand.getBeanClassName(), holder.getBeanName());
					}
				}
			}
		}

		// Process any @Import annotations
		//随后进行@Import注解的解析,此过程只是单纯的添加了一个ImportSelectorHolder
		processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

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

		// Process individual @Bean methods
		// 解析到带@Bean注解的方法,然后封装BeanMethod方法
		Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
		for (MethodMetadata methodMetadata : beanMethods) {
			configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
		}

		// Process default methods on interfaces
		// 处理接口上的默认的实现方法
		processInterfaces(configClass, sourceClass);

		// Process superclass, if any 处理超类
		if (sourceClass.getMetadata().hasSuperClass()) {
			String superclass = sourceClass.getMetadata().getSuperClassName();
			if (superclass != 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;
	}

}
processMemberClasses 获取配置类的嵌套内部类
class ConfigurationClassParser {
	//注册恰好是配置类本身的成员(嵌套)类
	private void processMemberClasses(ConfigurationClass configClass, SourceClass sourceClass,
			Predicate<String> filter) throws IOException {
		//获取配置类的嵌套内部类
		Collection<SourceClass> memberClasses = sourceClass.getMemberClasses();
		//如果嵌套内部类存在
		if (!memberClasses.isEmpty()) {
			//创建指定大小的内部类集合
			List<SourceClass> candidates = new ArrayList<>(memberClasses.size());
			for (SourceClass memberClass : memberClasses) {
				//验证嵌套类是否是配置类(即:通过@Configuration、@Component、@Bean等注解标注)
				if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
						!memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
					candidates.add(memberClass);
				}
			}
			//对嵌套内部类进行排序
			OrderComparator.sort(candidates);
			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();
					}
				}
			}
		}
	}
}
  • getMemberClasses
    上述处理嵌套内部类还有一个比较核心的方法getMemberClasses,此方法获取配置类的嵌套内部类:
class ConfigurationClassParser {
	private class SourceClass implements Ordered {
		public Collection<SourceClass> getMemberClasses() throws IOException {
			Object sourceToProcess = this.source;
			if (sourceToProcess instanceof Class) {
				Class<?> sourceClass = (Class<?>) sourceToProcess;
				try {
					Class<?>[] declaredClasses = sourceClass.getDeclaredClasses();
					List<SourceClass> members = new ArrayList<>(declaredClasses.length);
					for (Class<?> declaredClass : declaredClasses) {
						members.add(asSourceClass(declaredClass, DEFAULT_EXCLUSION_FILTER));
					}
					return members;
				}
				catch (NoClassDefFoundError err) {
					// getDeclaredClasses() failed because of non-resolvable dependencies
					// -> fall back to ASM below
					sourceToProcess = metadataReaderFactory.getMetadataReader(sourceClass.getName());
				}
			}

			// ASM-based resolution - safe for non-resolvable classes as well
			//基于ASM的解析,对于不可以解析的类也是安全的
			MetadataReader sourceReader = (MetadataReader) sourceToProcess;
			// 获取配置类的嵌套内部类
			String[] memberClassNames = sourceReader.getClassMetadata().getMemberClassNames();
			List<SourceClass> members = new ArrayList<>(memberClassNames.length);
			for (String memberClassName : memberClassNames) {
				try {
					//将嵌套类转换成简单的包装类,并且经过默认过滤器的过滤
					members.add(asSourceClass(memberClassName, DEFAULT_EXCLUSION_FILTER));
				}
				catch (IOException ex) {
					// Let's skip it if it's not resolvable - we're just looking for candidates
					if (logger.isDebugEnabled()) {
						logger.debug("Failed to resolve member class [" + memberClassName +
								"] - not considering it as a configuration class candidate");
					}
				}
			}
			return members;
		}
	}
}
componentScanParser.parse 解析componentScan注解

调用ComponentScanAnnotationParser 扫描包注解的解析器,方法内部定义了一个类路径扫描器,随后解析了注解上的一些属性,包括范围域、资源类型(.class)、是否懒加载、包路径加载、过滤器,随后调用Scanner的doScan方法,即ClassPathBeanDefinitionScanner 注册BeanDefinition的方法

class ComponentScanAnnotationParser {
	private final Environment environment;

	private final ResourceLoader resourceLoader;

	private final BeanNameGenerator beanNameGenerator;

	private final BeanDefinitionRegistry registry;

	public Set<BeanDefinitionHolder> parse(AnnotationAttributes componentScan, final String declaringClass) {
		ClassPathBeanDefinitionScanner scanner = new ClassPathBeanDefinitionScanner(this.registry,
				componentScan.getBoolean("useDefaultFilters"), this.environment, this.resourceLoader);

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

}
processImports

getImports得到的两个Import注解引入的类:AutoConfigurationImportSelector、AutoConfigurationPackages.Registrar,然后对两个导入候选类进行判断,对配置类进行判断,如果不是循环导入和 是在堆栈上链式导入,进行下一步解析;首先将配置类入栈,对导入候选类进行遍历循环处理。首先对AutoConfigurationPackages.Registrar类进行处理,符合 else if 判断,即instance of ImportBeanDefinitionRegistrar,符合导入BeanDefinition注册;随后对AutoConfigurationImportSelector进行解析,在对AutoConfigurationImportSelector进行解析的时候,由于符合invokeAwareMethods方法中的类型判断,所以进行包装处理,并返回实例对象。

class ConfigurationClassParser {
	private final DeferredImportSelectorHandler deferredImportSelectorHandler = new DeferredImportSelectorHandler();
	/**
	 * Returns {@code @Import} class, considering all meta-annotations.
	 */
	private Set<SourceClass> getImports(SourceClass sourceClass) throws IOException {
		Set<SourceClass> imports = new LinkedHashSet<>();
		Set<SourceClass> visited = new LinkedHashSet<>();
		collectImports(sourceClass, imports, visited);
		return imports;
	}

	private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
			Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
			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) {
					if (candidate.isAssignable(ImportSelector.class)) {
						// Candidate class is an ImportSelector -> delegate to it to determine imports
						Class<?> candidateClass = candidate.loadClass();
						ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
								this.environment, this.resourceLoader, this.registry);
						//获取排除类过滤器
						Predicate<String> selectorFilter = selector.getExclusionFilter();
						if (selectorFilter != null) {
							exclusionFilter = exclusionFilter.or(selectorFilter);
						}
						//符合延迟导入选择器,调用对应的handler进行处理,handler是在类初始化的时候,进行创建的
						if (selector instanceof DeferredImportSelector) {
							this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
						}
						else {
							String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
							Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
							processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
						}
					}
					else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
						// Candidate class is an ImportBeanDefinitionRegistrar ->
						// delegate to it to register additional bean definitions
						Class<?> candidateClass = candidate.loadClass();
						//candidateClass = AutoConfigurationPackages.Registrar,此处返回该类的实例对象
						ImportBeanDefinitionRegistrar registrar =
								ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
										this.environment, this.resourceLoader, this.registry);
						//随后将当前类配置为配置类的导入注册器ImportBeanDefinitionRegistrar,调用的是ConfigurationClass的方法
						configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
					}
					else {
						// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
						// process it as an @Configuration class
						this.importStack.registerImport(
								currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
						processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
					}
				}
			}
			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();
			}
		}
	}

}

*ConfiguraitonClass

/**
*表示用户定义的{@link Configuration @Configuration}类。<p>包含一组{@link Bean}方法,
*包括在类的祖先中定义的所有此类方法,以“扁平化”的方式。
*/
final class ConfigurationClass {

	@Nullable
	private String beanName;

	private final Set<ConfigurationClass> importedBy = new LinkedHashSet<>(1);

	private final Set<BeanMethod> beanMethods = new LinkedHashSet<>();

	private final Map<String, Class<? extends BeanDefinitionReader>> importedResources =
			new LinkedHashMap<>();

	private final Map<ImportBeanDefinitionRegistrar, AnnotationMetadata> importBeanDefinitionRegistrars =
			new LinkedHashMap<>();

	void addImportBeanDefinitionRegistrar(ImportBeanDefinitionRegistrar registrar, AnnotationMetadata importingClassMetadata) {
		this.importBeanDefinitionRegistrars.put(registrar, importingClassMetadata);
	}
}

*invokeAwareMethods

abstract class ParserStrategyUtils {
	private static void invokeAwareMethods(Object parserStrategyBean, Environment environment,
			ResourceLoader resourceLoader, BeanDefinitionRegistry registry, @Nullable ClassLoader classLoader) {

		if (parserStrategyBean instanceof Aware) {
			if (parserStrategyBean instanceof BeanClassLoaderAware && classLoader != null) {
				((BeanClassLoaderAware) parserStrategyBean).setBeanClassLoader(classLoader);
			}
			if (parserStrategyBean instanceof BeanFactoryAware && registry instanceof BeanFactory) {
				((BeanFactoryAware) parserStrategyBean).setBeanFactory((BeanFactory) registry);
			}
			if (parserStrategyBean instanceof EnvironmentAware) {
				((EnvironmentAware) parserStrategyBean).setEnvironment(environment);
			}
			if (parserStrategyBean instanceof ResourceLoaderAware) {
				((ResourceLoaderAware) parserStrategyBean).setResourceLoader(resourceLoader);
			}
		}
	}

}
deferredImportSelectorHandler.process()导入选择器的处理器

参考DeferredImportSelectorHandler

ConfigurationClassBeanDefinitionReader.loadBeanDefinitions(configClasses)

此方法对configClasses类进行解析,包括注册类中的BeanMethod、ImportedResources等

class ConfigurationClassBeanDefinitionReader {
	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;
		}

		if (configClass.isImported()) {
			//将configClass注册为一个AnnotationBeanDefinition
			registerBeanDefinitionForImportedConfigurationClass(configClass);
		}
		//获取配置类中的BeanMethod,并进行BeanDefinition注册
		for (BeanMethod beanMethod : configClass.getBeanMethods()) {
			loadBeanDefinitionsForBeanMethod(beanMethod);
		}
		//获取配置类中的ImportedResources进行加载
		loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
		//从注册器中获取需要注册的BeanDefinitions
		loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
	}

	private void registerBeanDefinitionForImportedConfigurationClass(ConfigurationClass configClass) {
		AnnotationMetadata metadata = configClass.getMetadata();
		AnnotatedGenericBeanDefinition configBeanDef = new AnnotatedGenericBeanDefinition(metadata);

		ScopeMetadata scopeMetadata = scopeMetadataResolver.resolveScopeMetadata(configBeanDef);
		configBeanDef.setScope(scopeMetadata.getScopeName());
		String configBeanName = this.importBeanNameGenerator.generateBeanName(configBeanDef, this.registry);
		AnnotationConfigUtils.processCommonDefinitionAnnotations(configBeanDef, metadata);

		BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(configBeanDef, configBeanName);
		definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);
		this.registry.registerBeanDefinition(definitionHolder.getBeanName(), definitionHolder.getBeanDefinition());
		configClass.setBeanName(configBeanName);

		if (logger.isTraceEnabled()) {
			logger.trace("Registered bean definition for imported class '" + configBeanName + "'");
		}
	}
}

ConfigurationClassParser.DeferredImportSelectorHandler 导入包处理

此方法对接上文中processImports 中AutoConfigurationImportSelector类的处理.DeferredImportSelectorHandler是ConfigurationClassParser的一个内部类。
在处理完configurationClass方法后,开始调用process方法对导入类进行处理,process方法中构建了一个GroupingHandler,调用了GroupingHandler的register方法循环对ImportSector进行处理,首先调用注册方法,随后调用handler.processGroupImports()方法。

class ConfigurationClassParser {
	private class DeferredImportSelectorHandler {

		private List<DeferredImportSelectorHolder> deferredImportSelectors = new ArrayList<>();

		/**
		 * 处理指定的{@link DeferredImportSelector}。如果正在收集递延的import *选择器,这将把该实例注册到列表中。
		 * 如果它们正在被处理,{@link DeferredImportSelector}
		 * 也会根据其{@link DeferredImportSelector. group}立即被处理。
		 * @param configClass the source configuration class
		 * @param importSelector the selector to handle
		 */
		public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
			//根据配置类和过滤器配置一个延迟导入选择器holder
			DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(configClass, importSelector);
			if (this.deferredImportSelectors == null) {
				DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
				handler.register(holder);
				handler.processGroupImports();
			}
			else {
				//将当期holder添加到容器中
				this.deferredImportSelectors.add(holder);
			}
		}

		public void process() {
			List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
			this.deferredImportSelectors = null;
			try {
				if (deferredImports != null) {
					DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
					deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
					deferredImports.forEach(handler::register);
					handler.processGroupImports();
				}
			}
			finally {
				this.deferredImportSelectors = new ArrayList<>();
			}
		}
	}

	private static class DeferredImportSelectorHolder {

		private final ConfigurationClass configurationClass;

		private final DeferredImportSelector importSelector;


		public DeferredImportSelectorHolder(ConfigurationClass configClass, DeferredImportSelector selector) {
			this.configurationClass = configClass;
			this.importSelector = selector;
		}

		public ConfigurationClass getConfigurationClass() {
			return this.configurationClass;
		}

		public DeferredImportSelector getImportSelector() {
			return this.importSelector;
		}
	}


}

AutoConfigurationImportSelector

getAutoConfigurationEntry方法首先根据注解类获取属性值,此处提供了一个EnableAutoConfiguration的注解返回值

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
		ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
	protected AutoConfigurationEntry getAutoConfigurationEntry(AnnotationMetadata annotationMetadata) {
		if (!isEnabled(annotationMetadata)) {
			return EMPTY_ENTRY;
		}
		//返回了注解内的两个属性值 exclude、excludeName
		AnnotationAttributes attributes = getAttributes(annotationMetadata);
		//然后根据过滤器加载配置类,此处从SpringFactory加载了132个工厂类
		List<String> configurations = getCandidateConfigurations(annotationMetadata, attributes);
		configurations = removeDuplicates(configurations);
		Set<String> exclusions = getExclusions(annotationMetadata, attributes);
		checkExcludedClasses(configurations, exclusions);
		configurations.removeAll(exclusions);
		//getConfigurationClassFilter()从SpringFactory加载类导入过滤器,然后对configurations进行过滤,然后剩下25个
		configurations = getConfigurationClassFilter().filter(configurations);
		fireAutoConfigurationImportEvents(configurations, exclusions);
		return new AutoConfigurationEntry(configurations, exclusions);
	}

	protected AnnotationAttributes getAttributes(AnnotationMetadata metadata) {
		String name = getAnnotationClass().getName();
		AnnotationAttributes attributes = AnnotationAttributes.fromMap(metadata.getAnnotationAttributes(name, true));
		Assert.notNull(attributes, () -> "No auto-configuration attributes found. Is " + metadata.getClassName()
				+ " annotated with " + ClassUtils.getShortName(name) + "?");
		return attributes;
	}

	/**
	 * Return the source annotation class used by the selector.
	 * @return the annotation class
	 */
	protected Class<?> getAnnotationClass() {
		return EnableAutoConfiguration.class;
	}

	protected List<String> getCandidateConfigurations(AnnotationMetadata metadata, AnnotationAttributes attributes) {
		//getSpringFactoriesLoaderFactoryClass方法返回的EnableAutoConfiguration
		List<String> configurations = SpringFactoriesLoader.loadFactoryNames(getSpringFactoriesLoaderFactoryClass(),
				getBeanClassLoader());
		Assert.notEmpty(configurations, "No auto configuration classes found in META-INF/spring.factories. If you "
				+ "are using a custom packaging, make sure that file is correct.");
		return configurations;
	}

}

ConfigurationClassParser.DeferredImportSelectorGroupingHandler

process方法中对 DeferredImportSelectorHolder 进行注册,此处得到的group为:AutoConfigurationImportSelector.AutoConfigurationGroup自动配置组,在createGroup(group)方法中,AutoConfigurationGroup继承了多个接口,在执行实例化的方法过程中,对AutoConfigurationGroup对象进行了包装处理,给多个成员属性赋值,方便工厂、资源的获取。并将实例化的对象包装成DeferredImportSelectorGrouping。

调用GroupingHandler的processGroupImports方法,方法内部调用了DeferredImportSelectorGrouping的getCandidateFilter方法获取候选类过滤器,调用DeferredImportSelectorGrouping的getImports方法获取导入类,getImport方法内部调用AutoConfigurationGroup的process方法。此方法从SpringFactory工厂中加载到25个ConfigurationClass,使用OnClassCondition、OnBeanCondition、OnWebApplicationCondition经过过滤。

0 = {DeferredImportSelector$Group$Entry@5447} "org.springframework.boot.autoconfigure.context.MessageSourceAutoConfiguration"
1 = {DeferredImportSelector$Group$Entry@5448} "org.springframework.boot.autoconfigure.context.PropertyPlaceholderAutoConfiguration"
2 = {DeferredImportSelector$Group$Entry@5449} "org.springframework.boot.autoconfigure.websocket.servlet.WebSocketServletAutoConfiguration"
3 = {DeferredImportSelector$Group$Entry@5450} "org.springframework.boot.autoconfigure.web.servlet.ServletWebServerFactoryAutoConfiguration"
4 = {DeferredImportSelector$Group$Entry@5451} "org.springframework.boot.autoconfigure.web.servlet.DispatcherServletAutoConfiguration"
5 = {DeferredImportSelector$Group$Entry@5452} "org.springframework.boot.autoconfigure.task.TaskExecutionAutoConfiguration"
6 = {DeferredImportSelector$Group$Entry@5453} "org.springframework.boot.autoconfigure.web.servlet.error.ErrorMvcAutoConfiguration"
7 = {DeferredImportSelector$Group$Entry@5454} "org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration"
8 = {DeferredImportSelector$Group$Entry@5455} "com.alibaba.boot.dubbo.autoconfigure.DubboAutoConfiguration"
9 = {DeferredImportSelector$Group$Entry@5456} "org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration"
10 = {DeferredImportSelector$Group$Entry@5457} "org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration"
11 = {DeferredImportSelector$Group$Entry@5458} "org.springframework.boot.autoconfigure.aop.AopAutoConfiguration"
12 = {DeferredImportSelector$Group$Entry@5459} "org.springframework.boot.autoconfigure.availability.ApplicationAvailabilityAutoConfiguration"
13 = {DeferredImportSelector$Group$Entry@5460} "org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration"
14 = {DeferredImportSelector$Group$Entry@5461} "org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration"
15 = {DeferredImportSelector$Group$Entry@5462} "org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration"
16 = {DeferredImportSelector$Group$Entry@5463} "org.springframework.boot.autoconfigure.context.LifecycleAutoConfiguration"
17 = {DeferredImportSelector$Group$Entry@5464} "org.springframework.boot.autoconfigure.http.HttpMessageConvertersAutoConfiguration"
18 = {DeferredImportSelector$Group$Entry@5465} "org.springframework.boot.autoconfigure.info.ProjectInfoAutoConfiguration"
19 = {DeferredImportSelector$Group$Entry@5466} "org.springframework.boot.autoconfigure.sql.init.SqlInitializationAutoConfiguration"
20 = {DeferredImportSelector$Group$Entry@5467} "org.springframework.boot.autoconfigure.task.TaskSchedulingAutoConfiguration"
21 = {DeferredImportSelector$Group$Entry@5468} "org.springframework.boot.autoconfigure.web.client.RestTemplateAutoConfiguration"
22 = {DeferredImportSelector$Group$Entry@5469} "org.springframework.boot.autoconfigure.web.embedded.EmbeddedWebServerFactoryCustomizerAutoConfiguration"
23 = {DeferredImportSelector$Group$Entry@5470} "org.springframework.boot.autoconfigure.web.servlet.HttpEncodingAutoConfiguration"
24 = {DeferredImportSelector$Group$Entry@5471} "org.springframework.boot.autoconfigure.web.servlet.MultipartAutoConfiguration"

然后继续调用processImports()对configurationClass进行处理,我们查看ConfigurationClassParser.processImports对configurationClass的处理

class ConfigurationClassParser {
	private class DeferredImportSelectorGroupingHandler {

		private final Map<Object, DeferredImportSelectorGrouping> groupings = new LinkedHashMap<>();

		private final Map<AnnotationMetadata, ConfigurationClass> configurationClasses = new HashMap<>();

		public void register(DeferredImportSelectorHolder deferredImport) {
			//加载类型
			Class<? extends Group> group = deferredImport.getImportSelector().getImportGroup();
			DeferredImportSelectorGrouping grouping = this.groupings.computeIfAbsent(
					(group != null ? group : deferredImport),
					key -> new DeferredImportSelectorGrouping(createGroup(group)));
			//添加实例
			grouping.add(deferredImport);
			//此处解析到的configurationClass为:com.bail.user.service.UserProviderBootstrap
			this.configurationClasses.put(deferredImport.getConfigurationClass().getMetadata(),
					deferredImport.getConfigurationClass());
		}

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

		private Group createGroup(@Nullable Class<? extends Group> type) {
			Class<? extends Group> effectiveType = (type != null ? type : DefaultDeferredImportSelectorGroup.class);
			return ParserStrategyUtils.instantiateClass(effectiveType, Group.class,
					ConfigurationClassParser.this.environment,
					ConfigurationClassParser.this.resourceLoader,
					ConfigurationClassParser.this.registry);
		}
	}
}

AutoConfigurationImportSelector.AutoConfigurationGroup

process方法内部调用AutoConfigurationImportSelector的getAutoConfigurationEntry方法

public class AutoConfigurationImportSelector implements DeferredImportSelector, BeanClassLoaderAware,
		ResourceLoaderAware, BeanFactoryAware, EnvironmentAware, Ordered {
	private static class AutoConfigurationGroup
			implements DeferredImportSelector.Group, BeanClassLoaderAware, BeanFactoryAware, ResourceLoaderAware {

		public void process(AnnotationMetadata annotationMetadata, DeferredImportSelector deferredImportSelector) {
			Assert.state(deferredImportSelector instanceof AutoConfigurationImportSelector,
					() -> String.format("Only %s implementations are supported, got %s",
							AutoConfigurationImportSelector.class.getSimpleName(),
							deferredImportSelector.getClass().getName()));
			AutoConfigurationEntry autoConfigurationEntry = ((AutoConfigurationImportSelector) deferredImportSelector)
					.getAutoConfigurationEntry(annotationMetadata);
			this.autoConfigurationEntries.add(autoConfigurationEntry);
			for (String importClassName : autoConfigurationEntry.getConfigurations()) {
				this.entries.putIfAbsent(importClassName, annotationMetadata);
			}
		}
	}

}

ConfigurationClassParser.DeferredImportSelectorGrouping

class ConfigurationClassParser {

private static final Predicate<String> DEFAULT_EXCLUSION_FILTER = className ->
			(className.startsWith("java.lang.annotation.") || className.startsWith("org.springframework.stereotype."));
	private static class DeferredImportSelectorGrouping {

		private final DeferredImportSelector.Group group;

		private final List<DeferredImportSelectorHolder> deferredImports = new ArrayList<>();

		DeferredImportSelectorGrouping(Group group) {
			this.group = group;
		}

		public void add(DeferredImportSelectorHolder deferredImport) {
			this.deferredImports.add(deferredImport);
		}

		/**
		 * Return the imports defined by the group.
		 * @return each import with its associated configuration class
		 */
		public Iterable<Group.Entry> getImports() {
			for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
				this.group.process(deferredImport.getConfigurationClass().getMetadata(),
						deferredImport.getImportSelector());
			}
			return this.group.selectImports();
		}

		public Predicate<String> getCandidateFilter() {
			Predicate<String> mergedFilter = DEFAULT_EXCLUSION_FILTER;
			for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
				Predicate<String> selectorFilter = deferredImport.getImportSelector().getExclusionFilter();
				if (selectorFilter != null) {
					mergedFilter = mergedFilter.or(selectorFilter);
				}
			}
			return mergedFilter;
		}
	}

}

ConfigurationClassParser.processImports

此处我们以MessageSourceAutoConfiguration为例,此处方法中configClass = com.bail.user.service.UserProviderBootstrap、
importCandidates为MessageSourceAutoConfiguration,将MessageSourceAutoConfiguration包装成ConfigurationClass,并进行处理。

class ConfigurationClassParser {
	private void processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
			Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
			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) {
					//此处对于导入类有三种类型的处理,MessageSourceAutoConfiguration是一个普通配置类
					if (candidate.isAssignable(ImportSelector.class)) {
						// Candidate class is an ImportSelector -> delegate to it to determine imports
						Class<?> candidateClass = candidate.loadClass();
						ImportSelector selector = ParserStrategyUtils.instantiateClass(candidateClass, ImportSelector.class,
								this.environment, this.resourceLoader, this.registry);
						Predicate<String> selectorFilter = selector.getExclusionFilter();
						if (selectorFilter != null) {
							exclusionFilter = exclusionFilter.or(selectorFilter);
						}
						if (selector instanceof DeferredImportSelector) {
							this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
						}
						else {
							String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
							Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);
							processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
						}
					}
					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 =
								ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
										this.environment, this.resourceLoader, this.registry);
						configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
					}
					else {
						// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
						// process it as an @Configuration class
						//不是ImportSelector 和ImportBeanDefinitionRegistrar ,当做Configuration class进行处理,com.bail.user.service.UserProviderBootstrap -> MessageSourceAutoConfiguration
						this.importStack.registerImport(
								currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
						processConfigurationClass(candidate.asConfigClass(configClass), exclusionFilter);
					}
				}
			}
			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();
			}
		}
	}

}
PropertySourcesPlaceholderConfigurer

属性占位符后置处理器,注入了属性源

public class PropertySourcesPlaceholderConfigurer extends PlaceholderConfigurerSupport implements EnvironmentAware {

	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
		if (this.propertySources == null) {
			this.propertySources = new MutablePropertySources();
			if (this.environment != null) {
				this.propertySources.addLast(
					new PropertySource<Environment>(ENVIRONMENT_PROPERTIES_PROPERTY_SOURCE_NAME, this.environment) {
						@Override
						@Nullable
						public String getProperty(String key) {
							return this.source.getProperty(key);
						}
					}
				);
			}
			try {
				PropertySource<?> localPropertySource =
						new PropertiesPropertySource(LOCAL_PROPERTIES_PROPERTY_SOURCE_NAME, mergeProperties());
				if (this.localOverride) {
					this.propertySources.addFirst(localPropertySource);
				}
				else {
					this.propertySources.addLast(localPropertySource);
				}
			}
			catch (IOException ex) {
				throw new BeanInitializationException("Could not load properties", ex);
			}
		}

		processProperties(beanFactory, new PropertySourcesPropertyResolver(this.propertySources));
		this.appliedPropertySources = this.propertySources;
	}
}

BeanFactoryPostProcessor层级

/**
*工厂钩子,允许自定义修改应用程序上下文的bean定义,调整上下文的底层bean工厂的bean属性值.
*
*适用于针对覆盖在应用程序上下文中配置的bean属性的系统管理员的自定义配置文件。 
*请参阅PropertyResourceConfigurer及其具体实现,了解解决此类配置需求的开箱即用的解决方案。  
*
*BeanFactoryPostProcessor可以与bean定义交互并修改它们,但不能与bean实例交互。
*样做可能会导致过早的bean实例化,违反容器并导致意外的副作用。 如果需要bean实例交互,则考虑实现BeanPostProcessor。  
*
*ApplicationContext在其bean定义中自动检测BeanFactoryPostProcessor bean,并在创建任何其他bean之前应用它们。
*BeanFactoryPostProcessor也可以用ConfigurableApplicationContext编程注册。 
*
*在ApplicationContext中被自动检测到的BeanFactoryPostProcessor bean将根据 priorityorordered和Ordered语义进行排序。
*相反,用ConfigurableApplicationContext编程注册的BeanFactoryPostProcessor bean将按照注册的顺序应用;
*通过实现prioritorderordered或Ordered接口表示的任何排序语义将被编程注册的后处理程序忽略。
*此外,对于BeanFactoryPostProcessor bean, @Order注释不被考虑。
*/
@FunctionalInterface
public interface BeanFactoryPostProcessor {

	/**
	 *在标准初始化之后修改应用程序上下文的内部bean工厂。 将加载所有bean定义,但还没有实例化任何bean。 
	 *这允许覆盖或添加属性,甚至可以添加到急于初始化的bean。 
	 * Modify the application context's internal bean factory after its standard
	 * initialization. All bean definitions will have been loaded, but no beans
	 * will have been instantiated yet. This allows for overriding or adding
	 * properties even to eager-initializing beans.
	 * @param beanFactory the bean factory used by the application context
	 * @throws org.springframework.beans.BeansException in case of errors
	 */
	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

BeanDefinitionRegistryPostProcessor

/**
*扩展到标准BeanFactoryPostProcessor SPI,允许在常规BeanFactoryPostProcessor检测开始之前注册更多的bean定义。
*特别是,BeanDefinitionRegistryPostProcessor可以注册进一步的bean定义,这些bean定义依次定义BeanFactoryPostProcessor实例。
*
*/
public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

	/**
	 *在标准初始化之后修改应用程序上下文的内部bean定义注册表。
	 *将加载所有常规bean定义,但还没有实例化任何bean。这允许在下一个后处理阶段开始之前添加进一步的bean定义。
	 *
	 * Modify the application context's internal bean definition registry after its
	 * standard initialization. All regular bean definitions will have been loaded,
	 * but no beans will have been instantiated yet. This allows for adding further
	 * bean definitions before the next post-processing phase kicks in.
	 * @param registry the bean definition registry used by the application context
	 * @throws org.springframework.beans.BeansException in case of errors
	 */
	void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}