Spring ConfigurationClassPostProcessor类详解

  • Post author:
  • Post category:其他



ConfigurationClassPostProcessor由AnnotationConfigApplicationContext注册成BeanDefinition到容器中,主要用来处理含有@PropertySource,@ComponentScan,@Bean,@Import,@ImportSource,@Configuration等注解的的类,ConfigurationClassPostProcessor实现了BeanDefinitionRegistryPostProcessor接口。我们主要来分析它的postProcessBeanDefinitionRegistry方法和postProcessBeanFactory方法。




postProcessBeanDefinitionRegistry方法

首先来看postProcessBeanDefinitionRegistry方法

	public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
		//获取到注册到容器中的beanDefinition的name
		String[] candidateNames = registry.getBeanDefinitionNames();
		
		//循环判断所有的beanDefinition
		for (String beanName : candidateNames) {
			BeanDefinition beanDef = registry.getBeanDefinition(beanName);
			//CONFIGURATION_CLASS_ATTRIBUTE该属性用于标注beanDefinition是否已经被处理过
			if (beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE) != null) {
				if (logger.isDebugEnabled()) {
					logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
				}
			}
			//checkConfigurationClassCandidate判断beanDefinition是否可以被处理
			else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
				//需要处理的beanDefinition加入到configCandidates容器中
				configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
			}
		}

		// Return immediately if no @Configuration classes were found
		//没有需要处理的beanDefinition,直接返回。
		if (configCandidates.isEmpty()) {
			return;
		}
		
		// Sort by previously determined @Order value, if applicable
		//对需要处理的beanDefinition进行排序
		configCandidates.sort((bd1, bd2) -> {
			int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
			int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
			return Integer.compare(i1, i2);
		});

		// Detect any custom bean name generation strategy supplied through the enclosing application context
		SingletonBeanRegistry sbr = null;
		if (registry instanceof SingletonBeanRegistry) {
			sbr = (SingletonBeanRegistry) registry;
			if (!this.localBeanNameGeneratorSet) {
				BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(
						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);
		
		//需要处理的beanDefinition
		Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
		//已经处理过的beanDefinition
		Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
		do {
			//具体的处理逻辑
			parser.parse(candidates);
			parser.validate();
				
			Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
			//移除处理过得类
			configClasses.removeAll(alreadyParsed);

			// Read the model and create bean definitions based on its content
			if (this.reader == null) {
				this.reader = new ConfigurationClassBeanDefinitionReader(
						registry, this.sourceExtractor, this.resourceLoader, this.environment,
						this.importBeanNameGenerator, parser.getImportRegistry());
			}
			//具体处理逻辑
			this.reader.loadBeanDefinitions(configClasses);
			alreadyParsed.addAll(configClasses);
			
			candidates.clear();
			//容器中的BeanDefinition更多,处理容器中未被处理BeanDefinition
			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
		//将ImportStack注册到容器中,ImportStack的imports中存入了被导入的类的类名和导入的类的元数据信息
		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();
		}
	}
	public static boolean checkConfigurationClassCandidate(
			BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {
		
		//BeanClassName都没有的beanDefinition不进行后续处理
		String className = beanDef.getBeanClassName();
		if (className == null || beanDef.getFactoryMethodName() != null) {
			return false;
		}

		AnnotationMetadata metadata;
		//AnnotatedBeanDefinition类型的beanDefinition(一般来说是被容器扫描到的,当然你也可以自己new出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();
		}
		//不是AnnotatedBeanDefinition类型的(一般来说不是被容器扫描到的),而是通过其他方式创建的其他类型的beanDefinition
		else if (beanDef instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) beanDef).hasBeanClass()) {
			// Check already loaded Class if present...
			// since we possibly can't even load the class file for this Class.
			Class<?> beanClass = ((AbstractBeanDefinition) beanDef).getBeanClass();
			//这些类型的不处理,这些类型在其他的地方会处理到
			if (BeanFactoryPostProcessor.class.isAssignableFrom(beanClass) ||
					BeanPostProcessor.class.isAssignableFrom(beanClass) ||
					AopInfrastructureBean.class.isAssignableFrom(beanClass) ||
					EventListenerFactory.class.isAssignableFrom(beanClass)) {
				return false;
			}
			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;
			}
		}
		
		Map<String, Object> config = metadata.getAnnotationAttributes(Configuration.class.getName());
		//如果被@Configuration注解修饰,且注解的proxyBeanMethods为true(默认为true)
		//full类型
		if (config != null && !Boolean.FALSE.equals(config.get("proxyBeanMethods"))) {
			beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
		}
		//isConfigurationCandidate:类中是否有Component,ComponentScan,Import,ImportResource,Bean这些注解
		//lite类型
		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.
		//是否有@Order注解
		Integer order = getOrder(metadata);
		if (order != null) {
			//设置order的值到beanDefinition中。
			beanDef.setAttribute(ORDER_ATTRIBUTE, order);
		}

		return true;
	}
	protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
		processConfigurationClass(new ConfigurationClass(metadata, beanName), DEFAULT_EXCLUSION_FILTER);
	}
	protected void processConfigurationClass(ConfigurationClass configClass, Predicate<String> filter) throws IOException {
		//处理@Conditional注解
		if (this.conditionEvaluator.shouldSkip(configClass.getMetadata(), ConfigurationPhase.PARSE_CONFIGURATION)) {
			return;
		}
		
		//第一次进来configurationClasses里面啥都没有
		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 sourceClass = asSourceClass(configClass, filter);
		do {
			//具体处理逻辑
			sourceClass = doProcessConfigurationClass(configClass, sourceClass, filter);
		}
		while (sourceClass != null);
		
		//收集处理的类到configurationClasses中
		this.configurationClasses.put(configClass, configClass);
	}
	public boolean shouldSkip(@Nullable AnnotatedTypeMetadata metadata, @Nullable ConfigurationPhase phase) {
		//false不跳过(需要处理改beanDefinition),true跳过
		//如果没有被@Conditional修饰
		if (metadata == null || !metadata.isAnnotated(Conditional.class.getName())) {
			return false;
		}
		
		//如果传入phase参数为null
		if (phase == null) {
			//属于AnnotationMetadata类型
			//isConfigurationCandidate:类中是否有Component,ComponentScan,Import,ImportResource,Bean这些注解
			//phase为ConfigurationPhase.PARSE_CONFIGURATION
			if (metadata instanceof AnnotationMetadata &&
					ConfigurationClassUtils.isConfigurationCandidate((AnnotationMetadata) metadata)) {
				return shouldSkip(metadata, ConfigurationPhase.PARSE_CONFIGURATION);
			}
			//否则phasephase为ConfigurationPhase.REGISTER_BEAN
			return shouldSkip(metadata, ConfigurationPhase.REGISTER_BEAN);
		}

		
		List<Condition> conditions = new ArrayList<>();
		//getConditionClasses获取@Conditional配置的value值(class类型(需要实现Condition接口,重写matches方法))
		for (String[] conditionClasses : getConditionClasses(metadata)) {
			for (String conditionClass : conditionClasses) {
				//实例化@Conditional配置的类
				Condition condition = getCondition(conditionClass, this.context.getClassLoader());
				conditions.add(condition);
			}
		}
		
		//排序(实现Ordered接口或者有@Order注解,)
		AnnotationAwareOrderComparator.sort(conditions);
		
		//循环所有的condition实例
		for (Condition condition : conditions) {
			ConfigurationPhase requiredPhase = null;
			//如果实现的是ConfigurationCondition接口,调用getConfigurationPhase方法获取requiredPhase
			if (condition instanceof ConfigurationCondition) {
				requiredPhase = ((ConfigurationCondition) condition).getConfigurationPhase();
			}
			//如果requiredPhase 为空 或者 requiredPhase和入参的phase一致
			//上述条件成立,则调用自己实现的matches方法
			if ((requiredPhase == null || requiredPhase == phase) && !condition.matches(this.context, metadata)) {
				return true;
			}
		}

		return false;
	}
	protected final SourceClass doProcessConfigurationClass(
			ConfigurationClass configClass, SourceClass sourceClass, Predicate<String> filter)
			throws IOException {
		
		//如果被@Component修饰
		if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
			// Recursively process any member (nested) classes first
			//处理内部类
			processMemberClasses(configClass, sourceClass, filter);
		}
		
		// Process any @PropertySource annotations
		for (AnnotationAttributes propertySource : AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), PropertySources.class,
				org.springframework.context.annotation.PropertySource.class)) {
			if (this.environment instanceof ConfigurableEnvironment) {
				//处理PropertySources和PropertySource注解
				processPropertySource(propertySource);
			}
			else {
				logger.info("Ignoring @PropertySource annotation on [" + sourceClass.getMetadata().getClassName() +
						"]. Reason: Environment must implement ConfigurableEnvironment");
			}
		}
		
		// Process any @ComponentScan annotations
		// 处理ComponentScans 和 ComponentScan注解
		Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
				sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
		if (!componentScans.isEmpty() &&
				!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
			for (AnnotationAttributes componentScan : componentScans) {
				// The config class is annotated with @ComponentScan -> perform the scan immediately
				//实际上处理逻辑和之前讲过的<component-scan>标签解析源码是一样的,这里就不再重复分析了。
				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
				//处理扫描到的beanDefinition
				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
					BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
					if (bdCand == null) {
						bdCand = holder.getBeanDefinition();
					}
					//如果该BeanDefinition需要处理
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
						//递归调用parse
						parse(bdCand.getBeanClassName(), holder.getBeanName());
					}
				}
			}
		}

		// Process any @Import annotations
		//getImports(sourceClass)获取@Import注解配置的value值(class对象)并且包装为SourceClass
		//处理@Import注解
		processImports(configClass, sourceClass, getImports(sourceClass), filter, true);

		// Process any @ImportResource annotations
		// 处理@ImportResource注解,@ImportResource注解用于引入额外的xml配置文件
		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) {
				//可以是占位符的形式配置xml文件路径,这里进行解析(占位符解析可以看之前的配置文件源码解析的文章)
				String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
				//收集xml配置文件
				configClass.addImportedResource(resolvedResource, readerClass);
			}
		}

		// Process individual @Bean methods
		//处理@Bean注解,收集@Bean标识的方法,封装为BeanMethod对象,添加到beanMethods容器中
		Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
		for (MethodMetadata methodMetadata : beanMethods) {
			configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
		}
			
		// Process default methods on interfaces
		//可以在接口上加@Bean注解,实现了接口的方法一样会被处理
		processInterfaces(configClass, sourceClass);
		
		// Process superclass, if any
		//如果有父类,且不是java开头的类型的类,且没有被处理过,接着处理父类
		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;
	}
	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) {
				//isConfigurationCandidate:内部类中是否有Component,ComponentScan,Import,ImportResource,Bean这些注解			
				if (ConfigurationClassUtils.isConfigurationCandidate(memberClass.getMetadata()) &&
						!memberClass.getMetadata().getClassName().equals(configClass.getMetadata().getClassName())) {
					//需要处理的内部类加入candidates
					candidates.add(memberClass);
				}
			}
			//排序(实现了Ordered接口或者PriorityOrdered接口)
			OrderComparator.sort(candidates);
			for (SourceClass candidate : candidates) {
				//importStack记录正在被处理的类
				if (this.importStack.contains(configClass)) {
					this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
				}
				else {
					this.importStack.push(configClass);
					try {
						//candidate.asConfigClass(configClass) 
						//将configClass(外部类)添加到candidate(内部类)的importedBy容器中
						//递归调用processConfigurationClass处理该类
						processConfigurationClass(candidate.asConfigClass(configClass), filter);
					}
					finally {
						this.importStack.pop();
					}
				}
			}
		}
	}
	private void processPropertySource(AnnotationAttributes propertySource) throws IOException {
		//获取name属性
		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");
		boolean ignoreResourceNotFound = propertySource.getBoolean("ignoreResourceNotFound");

		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 = this.resourceLoader.getResource(resolvedLocation);
				//将配置文件的key value值加入到environment的propertySources
				//多个PropertySource注解配置了相同name的合并到一个propertySources中
				//占位符解析的就会从propertySources中获取对应的值(详情可以看之前的配置文件解析的源码文章)
				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 processImports(ConfigurationClass configClass, SourceClass currentSourceClass,
			Collection<SourceClass> importCandidates, Predicate<String> exclusionFilter,
			boolean checkForCircularImports) {
		
		//如果importCandidates为空
		if (importCandidates.isEmpty()) {
			return;
		}
		
		if (checkForCircularImports && isChainedImportOnStack(configClass)) {
			this.problemReporter.error(new CircularImportProblem(configClass, this.importStack));
		}
		else {
			this.importStack.push(configClass);
			try {
				//循环处理@Import标签导入进来的类
				for (SourceClass candidate : importCandidates) {
					//如果实现了ImportSelector接口
					if (candidate.isAssignable(ImportSelector.class)) {
						// Candidate class is an ImportSelector -> delegate to it to determine imports
						Class<?> candidateClass = candidate.loadClass();
						//实例化被import进来的类(该类没有被Spring管理)
						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);
						}
						//如果实现的是DeferredImportSelector接口(继承了ImportSelector接口)
						if (selector instanceof DeferredImportSelector) {
							//这个接口的处理复杂一点。
							//可以重写getImportGroup方法返回实现了DeferredImportSelector.Group接口的类(该类还需要重写process方法和selectImports方法)的完整限定名
							this.deferredImportSelectorHandler.handle(configClass, (DeferredImportSelector) selector);
						}
						else {
							//直接调用自己重写的selectImports方法
							//入参为当前类(含有@Import注解的类)的Metadata
							String[] importClassNames = selector.selectImports(currentSourceClass.getMetadata());
							Collection<SourceClass> importSourceClasses = asSourceClasses(importClassNames, exclusionFilter);			
							//递归调用processImports处理importClassNames
							processImports(configClass, currentSourceClass, importSourceClasses, exclusionFilter, false);
						}
					}
					//如果实现了ImportBeanDefinitionRegistrar接口
					else if (candidate.isAssignable(ImportBeanDefinitionRegistrar.class)) {
						// Candidate class is an ImportBeanDefinitionRegistrar ->
						// delegate to it to register additional bean definitions
						Class<?> candidateClass = candidate.loadClass();
						//实例化被import进来的类
						ImportBeanDefinitionRegistrar registrar =
								ParserStrategyUtils.instantiateClass(candidateClass, ImportBeanDefinitionRegistrar.class,
										this.environment, this.resourceLoader, this.registry);
						//将该类加入到importBeanDefinitionRegistrars容器中(这里还没有调用到registerBeanDefinitions方法)
						configClass.addImportBeanDefinitionRegistrar(registrar, currentSourceClass.getMetadata());
					}
					//没实现那些的接口
					else {
						// Candidate class not an ImportSelector or ImportBeanDefinitionRegistrar ->
						// process it as an @Configuration class
						//将被Import的类和主动import的类型元数据信息加入到importStack的imports容器中
						this.importStack.registerImport(
								currentSourceClass.getMetadata(), candidate.getMetadata().getClassName());
						将configClass添加到candidate(被Import的类)的importedBy容器中
						//递归调用processConfigurationClass处理该类
						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();
			}
		}
	}
	 	public void handle(ConfigurationClass configClass, DeferredImportSelector importSelector) {
		    DeferredImportSelectorHolder holder = new DeferredImportSelectorHolder(configClass, importSelector);
			//deferredImportSelectors为空
			if (this.deferredImportSelectors == null) {
				DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
				handler.register(holder);
				handler.processGroupImports();
			}
			//只是加入到deferredImportSelectors中
			else {
				this.deferredImportSelectors.add(holder);
			}
	    }
	public void parse(Set<BeanDefinitionHolder> configCandidates) {
		for (BeanDefinitionHolder holder : configCandidates) {
			BeanDefinition bd = holder.getBeanDefinition();
			try {
				if (bd instanceof AnnotatedBeanDefinition) {
					parse(((AnnotatedBeanDefinition) bd).getMetadata(), holder.getBeanName());
				}
				else if (bd instanceof AbstractBeanDefinition && ((AbstractBeanDefinition) bd).hasBeanClass()) {
					parse(((AbstractBeanDefinition) bd).getBeanClass(), holder.getBeanName());
				}
				else {
					parse(bd.getBeanClassName(), holder.getBeanName());
				}
			}
			catch (BeanDefinitionStoreException ex) {
				throw ex;
			}
			catch (Throwable ex) {
				throw new BeanDefinitionStoreException(
						"Failed to parse configuration class [" + bd.getBeanClassName() + "]", ex);
			}
		}
		
		//在这里处理实现了DeferredImportSelector接口的类
		this.deferredImportSelectorHandler.process();
	}
		public void process() {
			List<DeferredImportSelectorHolder> deferredImports = this.deferredImportSelectors;
			this.deferredImportSelectors = null;
			try {
				if (deferredImports != null) {
					DeferredImportSelectorGroupingHandler handler = new DeferredImportSelectorGroupingHandler();
					//排序(如果实现了Ordered接口或者加上了@Order注解)
					deferredImports.sort(DEFERRED_IMPORT_COMPARATOR);
					//循环处理deferredImportSelectors,调用register方法
					deferredImports.forEach(handler::register);
					handler.processGroupImports();
				}
			}
			finally {
				this.deferredImportSelectors = new ArrayList<>();
			}
		}
		public void register(DeferredImportSelectorHolder deferredImport) {
			//调用getImportGroup方法,返回实现了Group接口的类
			Class<? extends Group> group = deferredImport.getImportSelector().getImportGroup();
			//如果不为空,也就是重写getImportGroup方法,则groupings放入的是实现了group接口的实例
			//如果为空,就是没重写,默认返回null,则groupings放入的实现了DeferredImportSelector接口的本身的实例
			DeferredImportSelectorGrouping grouping = this.groupings.computeIfAbsent(
					(group != null ? group : deferredImport),
					key -> new DeferredImportSelectorGrouping(createGroup(group)));
			grouping.add(deferredImport);
			this.configurationClasses.put(deferredImport.getConfigurationClass().getMetadata(),
					deferredImport.getConfigurationClass());
		}
		private Group createGroup(@Nullable Class<? extends Group> type) {
			//如果group不为空,则effectiveType为自己的group的类型
			//如果group为空,则effectiveType为默认的DefaultDeferredImportSelectorGroup
			Class<? extends Group> effectiveType = (type != null ? type : DefaultDeferredImportSelectorGroup.class);
			//实例化effectiveType
			return ParserStrategyUtils.instantiateClass(effectiveType, Group.class,
					ConfigurationClassParser.this.environment,
					ConfigurationClassParser.this.resourceLoader,
					ConfigurationClassParser.this.registry);
		}
		public void processGroupImports() {
			//循环groupings中所有group实例
			for (DeferredImportSelectorGrouping grouping : this.groupings.values()) {
				Predicate<String> exclusionFilter = grouping.getCandidateFilter();
				//调用group的getImports方法
				grouping.getImports().forEach(entry -> {
					ConfigurationClass configurationClass = this.configurationClasses.get(entry.getMetadata());
					try {
						//递归调用processImports
						processImports(configurationClass, asSourceClass(configurationClass, exclusionFilter),
								Collections.singleton(asSourceClass(entry.getImportClassName(), exclusionFilter)),
								exclusionFilter, false);
					}
					catch (BeanDefinitionStoreException ex) {
						throw ex;
					}
					catch (Throwable ex) {
						throw new BeanDefinitionStoreException(
								"Failed to process import candidates for configuration class [" +
										configurationClass.getMetadata().getClassName() + "]", ex);
					}
				});
			}
		}
	public Iterable<Group.Entry> getImports() {
		for (DeferredImportSelectorHolder deferredImport : this.deferredImports) {
			//调用group实例的process方法
			this.group.process(deferredImport.getConfigurationClass().getMetadata(),
					deferredImport.getImportSelector());
		}
		//调用group实例的selectImports方法
		return this.group.selectImports();
	}
	private static class DefaultDeferredImportSelectorGroup implements Group {

		private final List<Entry> imports = new ArrayList<>();
		
		@Override
		public void process(AnnotationMetadata metadata, DeferredImportSelector selector) {
			//调用ImportSelector接口对应的selectImports方法,
			for (String importClassName : selector.selectImports(metadata)) {
				this.imports.add(new Entry(metadata, importClassName));
			}
		}

		@Override
		public Iterable<Entry> selectImports() {
			return this.imports;
		}
	}
	public void loadBeanDefinitions(Set<ConfigurationClass> configurationModel) {
		TrackedConditionEvaluator trackedConditionEvaluator = new TrackedConditionEvaluator();
		//循环处理configClass 
		for (ConfigurationClass configClass : configurationModel) {
			loadBeanDefinitionsForConfigurationClass(configClass, trackedConditionEvaluator);
		}
	}
	private void loadBeanDefinitionsForConfigurationClass(
			ConfigurationClass configClass, TrackedConditionEvaluator trackedConditionEvaluator) {
		
		//处理@Conditional注解
		if (trackedConditionEvaluator.shouldSkip(configClass)) {
			//如果该类跳过处理,则移除该类和该类import进来的类
			String beanName = configClass.getBeanName();
			if (StringUtils.hasLength(beanName) && this.registry.containsBeanDefinition(beanName)) {
				this.registry.removeBeanDefinition(beanName);
			}
			this.importRegistry.removeImportingClass(configClass.getMetadata().getClassName());
			return;
		}
		
		//判断importedBy容器是否为空,也就是判断该类是否是被import进来的类(@Import注解,内部类)
		if (configClass.isImported()) {
			//将该类创建为BeanDefinition注册到容器中
			registerBeanDefinitionForImportedConfigurationClass(configClass);
		}
		//如果该类中有@Bean注解标识的方法
		for (BeanMethod beanMethod : configClass.getBeanMethods()) {
			//会判断@Bean方法上的@Conditional注解
			//创建该类的BeanDefinition注册到容器中
			//其中该BeanDefinition的factoryMethodName为@Bean标识的方法名,factoryBeanName为configClass对应的类的BeanName,如果是静态方法则BeanClassName为configClass对应的类
			loadBeanDefinitionsForBeanMethod(beanMethod);
		}
		
		//处理@ImportResource注解引入的xml配置文件(解析流程已经在Spring标签解析源码分析过了)
		loadBeanDefinitionsFromImportedResources(configClass.getImportedResources());
		//这里循环importBeanDefinitionRegistrars容器中的类调用registerBeanDefinitions方法
		loadBeanDefinitionsFromRegistrars(configClass.getImportBeanDefinitionRegistrars());
	}



postProcessBeanFactory方法

再来看postProcessBeanFactory方法,这里说一下@Configuration类的full类型,当手动调用@Bean标注的方法时,拿到的永远是同一个对象。

	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
		//省略部分源码
		
		//看这里
		enhanceConfigurationClasses(beanFactory);
		//将ImportAwareBeanPostProcessor添加到beanPostProcessor容器中
		beanFactory.addBeanPostProcessor(new ImportAwareBeanPostProcessor(beanFactory));
	}
	public void enhanceConfigurationClasses(ConfigurableListableBeanFactory beanFactory) {
		Map<String, AbstractBeanDefinition> configBeanDefs = new LinkedHashMap<>();
		//循环所有的BeanDefinition
		for (String beanName : beanFactory.getBeanDefinitionNames()) {
			BeanDefinition beanDef = beanFactory.getBeanDefinition(beanName);
			Object configClassAttr = beanDef.getAttribute(ConfigurationClassUtils.CONFIGURATION_CLASS_ATTRIBUTE);
			MethodMetadata methodMetadata = null;
			if (beanDef instanceof AnnotatedBeanDefinition) {
				methodMetadata = ((AnnotatedBeanDefinition) beanDef).getFactoryMethodMetadata();
			}
			if ((configClassAttr != null || methodMetadata != null) && beanDef instanceof AbstractBeanDefinition) {
				// Configuration class (full or lite) or a configuration-derived @Bean method
				// -> resolve bean class at this point...
				AbstractBeanDefinition abd = (AbstractBeanDefinition) beanDef;
				if (!abd.hasBeanClass()) {
					try {
						abd.resolveBeanClass(this.beanClassLoader);
					}
					catch (Throwable ex) {
						throw new IllegalStateException(
								"Cannot load configuration class: " + beanDef.getBeanClassName(), ex);
					}
				}
			}
			//如果BeanDefinition为full类型,加入到configBeanDefs容器中
			if (ConfigurationClassUtils.CONFIGURATION_CLASS_FULL.equals(configClassAttr)) {
				if (!(beanDef instanceof AbstractBeanDefinition)) {
					throw new BeanDefinitionStoreException("Cannot enhance @Configuration bean definition '" +
							beanName + "' since it is not stored in an AbstractBeanDefinition subclass");
				}
				else if (logger.isInfoEnabled() && beanFactory.containsSingleton(beanName)) {
					logger.info("Cannot enhance @Configuration bean definition '" + beanName +
							"' since its singleton instance has been created too early. The typical cause " +
							"is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor " +
							"return type: Consider declaring such methods as 'static'.");
				}
				configBeanDefs.put(beanName, (AbstractBeanDefinition) beanDef);
			}
		}
		//configBeanDefs为空,直接返回
		if (configBeanDefs.isEmpty()) {
			// nothing to enhance -> return immediately
			return;
		}
		
		//循环处理configBeanDefs中的beanDefinition
		ConfigurationClassEnhancer enhancer = new ConfigurationClassEnhancer();
		for (Map.Entry<String, AbstractBeanDefinition> entry : configBeanDefs.entrySet()) {
			AbstractBeanDefinition beanDef = entry.getValue();
			// If a @Configuration class gets proxied, always proxy the target class
			beanDef.setAttribute(AutoProxyUtils.PRESERVE_TARGET_CLASS_ATTRIBUTE, Boolean.TRUE);
			// Set enhanced subclass of the user-specified bean class
			Class<?> configClass = beanDef.getBeanClass();
			//对full类型的beanDefinition生成cglib代理类,来看
			Class<?> enhancedClass = enhancer.enhance(configClass, this.beanClassLoader);
			if (configClass != enhancedClass) {
				if (logger.isTraceEnabled()) {
					logger.trace(String.format("Replacing bean definition '%s' existing class '%s' with " +
							"enhanced class '%s'", entry.getKey(), configClass.getName(), enhancedClass.getName()));
				}
				//将该beanDefinition的class类型改为代理类!!!
				beanDef.setBeanClass(enhancedClass);
			}
		}
	}

重点来看代理类的拦截逻辑 : BeanFactoryAwareMethodInterceptor ,BeanMethodInterceptor

	private static class BeanFactoryAwareMethodInterceptor implements MethodInterceptor, ConditionalCallback {

		@Override
		@Nullable
		public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
			//给生成的代理类中的BEAN_FACTORY_FIELD($$beanFactory)字段赋值为beanFactory
			Field field = ReflectionUtils.findField(obj.getClass(), BEAN_FACTORY_FIELD);
			Assert.state(field != null, "Unable to find generated BeanFactory field");
			field.set(obj, args[0]);

			// Does the actual (non-CGLIB) superclass implement BeanFactoryAware?
			// If so, call its setBeanFactory() method. If not, just exit.
			//如果代理类的父类(也就是被代理类)实现了BeanFactoryAware接口
			if (BeanFactoryAware.class.isAssignableFrom(ClassUtils.getUserClass(obj.getClass().getSuperclass()))) {
				//调用被代理的方法
				return proxy.invokeSuper(obj, args);
			}
			return null;
		}
		
		//isMatch通过才会拦截
		@Override
		public boolean isMatch(Method candidateMethod) {
			return isSetBeanFactory(candidateMethod);
		}
		
		//调用的是否为BeanFactoryAware接口的setBeanFactory方法
		public static boolean isSetBeanFactory(Method candidateMethod) {
			return (candidateMethod.getName().equals("setBeanFactory") &&
					candidateMethod.getParameterCount() == 1 &&
					BeanFactory.class == candidateMethod.getParameterTypes()[0] &&
					BeanFactoryAware.class.isAssignableFrom(candidateMethod.getDeclaringClass()));
		}
	}
	private static class BeanMethodInterceptor implements MethodInterceptor, ConditionalCallback {

	
		@Override
		@Nullable
		public Object intercept(Object enhancedConfigInstance, Method beanMethod, Object[] beanMethodArgs,
					MethodProxy cglibMethodProxy) throws Throwable {

			ConfigurableBeanFactory beanFactory = getBeanFactory(enhancedConfigInstance);
			String beanName = BeanAnnotationHelper.determineBeanNameFor(beanMethod);

			// Determine whether this bean is a scoped-proxy
			//方法上有@Scope注解
			if (BeanAnnotationHelper.isScopedProxy(beanMethod)) {
				String scopedBeanName = ScopedProxyCreator.getTargetBeanName(beanName);
				if (beanFactory.isCurrentlyInCreation(scopedBeanName)) {
					beanName = scopedBeanName;
				}
			}

			
			//是否是实现了factoryBean接口的bean
			if (factoryContainsBean(beanFactory, BeanFactory.FACTORY_BEAN_PREFIX + beanName) &&
					factoryContainsBean(beanFactory, beanName)) {
				//获取到bean
				Object factoryBean = beanFactory.getBean(BeanFactory.FACTORY_BEAN_PREFIX + beanName);
				if (factoryBean instanceof ScopedProxyFactoryBean) {
					// Scoped proxy factory beans are a special case and should not be further proxied
				}
				else {
					// It is a candidate FactoryBean - go ahead with enhancement
					//给该bean创建代理
					return enhanceFactoryBean(factoryBean, beanMethod.getReturnType(), beanFactory, beanName);
				}
			}
			
			//判断currentlyInvokedFactoryMethod是否是该方法
			//当Spring实例化bean调用beanDefinition中的factoryMethodName对应的方法时,currentlyInvokedFactoryMethod会设置成该方法
			if (isCurrentlyInvokedFactoryMethod(beanMethod)) {
				if (logger.isInfoEnabled() &&
						BeanFactoryPostProcessor.class.isAssignableFrom(beanMethod.getReturnType())) {
					logger.info(String.format("@Bean method %s.%s is non-static and returns an object " +
									"assignable to Spring's BeanFactoryPostProcessor interface. This will " +
									"result in a failure to process annotations such as @Autowired, " +
									"@Resource and @PostConstruct within the method's declaring " +
									"@Configuration class. Add the 'static' modifier to this method to avoid " +
									"these container lifecycle issues; see @Bean javadoc for complete details.",
							beanMethod.getDeclaringClass().getSimpleName(), beanMethod.getName()));
				}
				//直接调用被代理类的方法
				return cglibMethodProxy.invokeSuper(enhancedConfigInstance, beanMethodArgs);
			}
			
			//看这里
			return resolveBeanReference(beanMethod, beanMethodArgs, beanFactory, beanName);
		}

		private Object resolveBeanReference(Method beanMethod, Object[] beanMethodArgs,
				ConfigurableBeanFactory beanFactory, String beanName) {
			

			try {
				
				//省略部分源码

				//从beanFactory获取bean
				Object beanInstance = (useArgs ? beanFactory.getBean(beanName, beanMethodArgs) :
						beanFactory.getBean(beanName));
						
				//省略部分源码
				
				//@Bean的方法调用了其他的@Bean方法
				//currentlyInvokedFactoryMethod查看是否有值
				Method currentlyInvoked = SimpleInstantiationStrategy.getCurrentlyInvokedFactoryMethod();
				if (currentlyInvoked != null) {
					//获取当前@Bean方法的beanName
					String outerBeanName = BeanAnnotationHelper.determineBeanNameFor(currentlyInvoked);
					//注册bean的依赖关系
					beanFactory.registerDependentBean(beanName, outerBeanName);
				}
				//返回从beanFactory中获取的bean
				return beanInstance;
			}
			finally {
				if (alreadyInCreation) {
					beanFactory.setCurrentlyInCreation(beanName, true);
				}
			}
		}
		
		@Override
		public boolean isMatch(Method candidateMethod) {
			return (candidateMethod.getDeclaringClass() != Object.class &&
					//如果调用的不是BeanFactoryAware接口的setBeanFactory方法
					!BeanFactoryAwareMethodInterceptor.isSetBeanFactory(candidateMethod) &&
					//调用的方法被@Bean修饰
					BeanAnnotationHelper.isBeanAnnotated(candidateMethod));
		}
		
		//获取BEAN_FACTORY_FIELD($$beanFactory)字段
		private ConfigurableBeanFactory getBeanFactory(Object enhancedConfigInstance) {
			Field field = ReflectionUtils.findField(enhancedConfigInstance.getClass(), BEAN_FACTORY_FIELD);
			Assert.state(field != null, "Unable to find generated bean factory field");
			Object beanFactory = ReflectionUtils.getField(field, enhancedConfigInstance);
			Assert.state(beanFactory != null, "BeanFactory has not been injected into @Configuration class");
			Assert.state(beanFactory instanceof ConfigurableBeanFactory,
					"Injected BeanFactory is not a ConfigurableBeanFactory");
			return (ConfigurableBeanFactory) beanFactory;
		}
		
		private Object enhanceFactoryBean(final Object factoryBean, Class<?> exposedType,
				final ConfigurableBeanFactory beanFactory, final String beanName) {

			try {
				Class<?> clazz = factoryBean.getClass();
				//如果类被final修饰
				boolean finalClass = Modifier.isFinal(clazz.getModifiers());
				//如果getObject方法被final修饰
				boolean finalMethod = Modifier.isFinal(clazz.getMethod("getObject").getModifiers());
				//(cglib动态代理要继承被代理类和重写方法)
				if (finalClass || finalMethod) {
					//如果@Bean方法返回的类型是一个接口类型,(jdk动态代理继承Proxy和实现对应的接口)
					if (exposedType.isInterface()) {
						if (logger.isTraceEnabled()) {
							logger.trace("Creating interface proxy for FactoryBean '" + beanName + "' of type [" +
									clazz.getName() + "] for use within another @Bean method because its " +
									(finalClass ? "implementation class" : "getObject() method") +
									" is final: Otherwise a getObject() call would not be routed to the factory.");
						}
						//jdk代理
						return createInterfaceProxyForFactoryBean(factoryBean, exposedType, beanFactory, beanName);
					}
					else {
						if (logger.isDebugEnabled()) {
							logger.debug("Unable to proxy FactoryBean '" + beanName + "' of type [" +
									clazz.getName() + "] for use within another @Bean method because its " +
									(finalClass ? "implementation class" : "getObject() method") +
									" is final: A getObject() call will NOT be routed to the factory. " +
									"Consider declaring the return type as a FactoryBean interface.");
						}
						return factoryBean;
					}
				}
			}
			catch (NoSuchMethodException ex) {
				// No getObject() method -> shouldn't happen, but as long as nobody is trying to call it...
			}
			
			//cglib代理
			return createCglibProxyForFactoryBean(factoryBean, beanFactory, beanName);
		}

		private Object createInterfaceProxyForFactoryBean(final Object factoryBean, Class<?> interfaceType,
				final ConfigurableBeanFactory beanFactory, final String beanName) {
			
			//返回jdk代理对象
			return Proxy.newProxyInstance(
					factoryBean.getClass().getClassLoader(), new Class<?>[] {interfaceType},
					(proxy, method, args) -> {
						//调用getObject方法时,从容器中获取bean返回
						if (method.getName().equals("getObject") && args == null) {
							return beanFactory.getBean(beanName);
						}
						return ReflectionUtils.invokeMethod(method, factoryBean, args);
					});
		}
		private Object createCglibProxyForFactoryBean(final Object factoryBean,
				final ConfigurableBeanFactory beanFactory, final String beanName) {
			
			//生成cglib代理对象
			Enhancer enhancer = new Enhancer();
			enhancer.setSuperclass(factoryBean.getClass());
			enhancer.setNamingPolicy(SpringNamingPolicy.INSTANCE);
			enhancer.setCallbackType(MethodInterceptor.class);

			
			Class<?> fbClass = enhancer.createClass();
			Object fbProxy = null;

			//省略部分源码

			((Factory) fbProxy).setCallback(0, (MethodInterceptor) (obj, method, args, proxy) -> {
				//调用getObject方法时,从容器中获取bean返回
				if (method.getName().equals("getObject") && args.length == 0) {
					return beanFactory.getBean(beanName);
				}
				return proxy.invoke(factoryBean, args);
			});

			return fbProxy;
		}
	private static class ImportAwareBeanPostProcessor extends InstantiationAwareBeanPostProcessorAdapter {

		private final BeanFactory beanFactory;

		public ImportAwareBeanPostProcessor(BeanFactory beanFactory) {
			this.beanFactory = beanFactory;
		}

		@Override
		public Object postProcessBeforeInitialization(Object bean, String beanName) {
			//实现了ImportAware接口的类处理
			if (bean instanceof ImportAware) {
				//获取ImportStack
				ImportRegistry ir = this.beanFactory.getBean(IMPORT_REGISTRY_BEAN_NAME, ImportRegistry.class);
				//被导入的类从ImportStack拿到主动导入的类元数据
				AnnotationMetadata importingClass = ir.getImportingClassFor(ClassUtils.getUserClass(bean).getName());
				if (importingClass != null) {
					//元数据信息作为入参调用ImportAware接口对应的方法
					((ImportAware) bean).setImportMetadata(importingClass);
				}
			}
			return bean;
		}
	}

到此ConfigurationClassPostProcessor类就分析的差不多了。



版权声明:本文为weixin_42103620原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。