spring源碼(二)——初探ConfigurationClassPostProcessor

前言

上一篇博客針對spring關於bean的註冊梳理到了BeanPostProcessor,同時梳理到了bean的註冊,整體看下來厚些凌亂,這篇博客會順帶回顧上篇博客的內容,然後梳理在BeanFactory中refresh操作的一些細節。

回顧

開始的實例代碼

public class TestConfig {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext annotationConfigApplicationContext =
				new AnnotationConfigApplicationContext();
		annotationConfigApplicationContext.register(AppConfigTest.class);
		annotationConfigApplicationContext.refresh();
		TestBean bean = annotationConfigApplicationContext.getBean(TestBean.class);
		TestBean testBean = annotationConfigApplicationContext.getBean(TestBean.class);
	}
}

上篇博客說道,在構造函數中,會實例化一個scanner和一個reader

/**
 * Create a new AnnotationConfigApplicationContext that needs to be populated
 * through {@link #register} calls and then manually {@linkplain #refresh refreshed}.
 */
public AnnotationConfigApplicationContext() {
	//創建一個beanDefinition的讀取器——BeanDefinitionReader
    //TODO:就是在這裏頭,完成了6個關鍵的類的實例化
	this.reader = new AnnotatedBeanDefinitionReader(this);
	//實例化了一個掃描器,但是spring真正的自動掃描並不是靠這個完成的
	this.scanner = new ClassPathBeanDefinitionScanner(this);
}

之後開始註冊bean並刷新BeanFactory容器

/**
 * 主要就是register和refresh方法,上一篇博客已經梳理了一下register
 */
public AnnotationConfigApplicationContext(Class<?>... componentClasses) {
	this();//這裏構建了一個類的掃描器和一個BeanDefinitionReader的讀取器
	register(componentClasses);
	refresh();
}

register方法就是上篇博客中的主要內容。上篇博客中還提到,在構造方法中完成主要的6個內部類的註冊。這六個類分別如下

//new AnnotatedBeanDefinitionReader(this);這行代碼的底層就會完成下面6個類的實例化
//唯一的一個BeanFactoryPostProcessor,實際對應的是ConfigurationClassPostProcessor
internalConfigurationAnnotationProcessor//這個非常重要,這篇博客大部分的內容與這個有關
//其餘四個是BeanPostProcessor
internalEventListenerFactory
internalEventListenerProcessor
internalPersistenceAnnotationProcessor
internalAutowiredAnnotationProcessor
internalCommonAnnotationProcessor

源碼中如下

在這裏插入圖片描述

接着refresh方法說開去

直接進入refresh方法,這個方法中如下所示

//AbstractApplicationContext 中的第515行
@Override
public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		//TODO :refresh容器的前記錄一些時間戳的信息,並不重要
		prepareRefresh();
		// Tell the subclass to refresh the internal bean factory.
		//TODO : 獲取當前容器對應的工廠ConfigurableListableBeanFactory
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
		// Prepare the bean factory for use in this context.
		//TODO:爲beanFactory的refresh構建一些類
		prepareBeanFactory(beanFactory);
		try {
			// Allows post-processing of the bean factory in context subclasses.
			//TODO:注入一些BeanFactory的屬性
			postProcessBeanFactory(beanFactory);
			// Invoke factory processors registered as beans in the context.
			//TODO: 調用BeanFactory的後置處理器 BeanFactoryPostProcessor
			invokeBeanFactoryPostProcessors(beanFactory);
			//後面的暫時省略
		}
		catch (BeansException ex) {
			//後面的暫時省略
		}
		finally {
			//後面的暫時省略
		}
	}
}

前面兩個方法不重要,可以直接看prepareBeanFactory()方法

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	//TODO:前三行不太重要
	beanFactory.setBeanClassLoader(getClassLoader());
    //TODO:增加bean表達式解釋器,後面再總結
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
    //TODO:對象與String類型的轉換,比如<property ref = "test"/>需要根據test轉換成指定的bean對象
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	//TODO:爲每一個bean加入一個後置處理器
    //TODO:爲什麼有些bean實現了ApplicationContextAware就能自動注入ApplicationContext,原因就在這裏
	// Configure the bean factory with context callbacks.
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

	//TODO: 忽略掉以下六個類型的依賴注入
	beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
	beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);

	// BeanFactory interface not registered as resolvable type in a plain factory.
	// MessageSource registered (and found for autowiring) as a bean.
    //TODO:替換當前BeanFactory的一些依賴
	beanFactory.registerResolvableDependency(BeanFactory.class, beanFactory);
	beanFactory.registerResolvableDependency(ResourceLoader.class, this);
	beanFactory.registerResolvableDependency(ApplicationEventPublisher.class, this);
	beanFactory.registerResolvableDependency(ApplicationContext.class, this);

	// Register early post-processor for detecting inner beans as ApplicationListeners.
    //TODO:不重要
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
	//TODO:注入spring的環境和屬性對象(environment和properties)
	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}

之後refresh方法中的postProcessBeanFactory這個方法沒有任何實現,這個可以直接忽略,下面進入refresh方法中的invokeBeanFactoryPostProcessors方法。

// AbstractApplicationContext中的第713行,主要作用是執行自定義的BeanFactoryPostProcessor和spring自定義的BeanFactoryPostProcessor
/**
 * Instantiate and invoke all registered BeanFactoryPostProcessor beans,
 * respecting explicit order if given.
 * <p>Must be called before singleton instantiation.
 */
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	//TODO:通過委託對象調用指定的BeanFactoryPostProcessor(這裏是調用自定義的BeanFactoryPostProcessor)
    //TODO:注意一下,這裏非常重要,如果我們自定義的BeanFactoryPostProcessor沒有顯示的通過代碼add加入到容器中,則這裏也無法獲取到。
    //TODO:同時,這裏只是獲取自定義的BeanFactoryPostProcessor,ConfigurationClassPostProcessor並不會得到。
    //TODO:這個集合也是定義在AbstractApplicationContext中,屬性爲: BeanFactoryPostProcessors to apply on refresh. 
	private final List<BeanFactoryPostProcessor> beanFactoryPostProcessors = new ArrayList<>();
	PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());

	// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
	// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
	if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}
}

這個方法有幾個需要注意的,getBeanFactoryPostProcessors()方法中是獲取自定義的BeanFactoryPostProcessor,無法獲取spring內部自定義的BeanFactoryPostProcessor接口。進入到PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()方法中,這個方法賊長也賊複雜。其中有幾個List集合需要說明一下

List<BeanFactoryPostProcessor> regularPostProcessors; //存放自定義的BeanFactoryPostProcessor

List<BeanDefinitionRegistryPostProcessor> registryProcessors;//存放自定義的BeanDefinitionRegistryPostProcessor

List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors;//存放spring內部自定義的BeanDefinitionRegistryPostProcessor

spring中該方法的源碼

//PostProcessorRegistrationDelegate 中的第56行
//TODO : 真正的調用BeanFactoryPostProcessor的後置處理器
public static void invokeBeanFactoryPostProcessors(
		ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

	// Invoke BeanDefinitionRegistryPostProcessors first, if any.
	Set<String> processedBeans = new HashSet<>();

	//TODO:如果BeanFactory是一個註冊器(這個好像必會進入)
	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

		//TODO:這裏定義了兩個集合,一個是BeanFactoryPostProcessor,一個是BeanDefinitionRegistryPostProcessor
		//TODO:放自定義的BeanFactoryPostProcessor
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
		//TODO:BeanDefinitionRegistryPostProcessor只是繼承了BeanFactoryPostProcessor接口而已
		//TODO:放自定義的BeanDefinitionRegistryPostProcessor
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();

		//TODO : 遍歷傳入過來的集合beanFactoryPostProcessors
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			//TODO:如果自定義的BeanFactoryPostProcessor實現了BeanDefinitionRegistryPostProcessor接口
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {//TODO:如果是BeanDefinitionRegistryPostProcessor
				BeanDefinitionRegistryPostProcessor registryProcessor =
						(BeanDefinitionRegistryPostProcessor) postProcessor;
				registryProcessor.postProcessBeanDefinitionRegistry(registry);//TODO:調用postProcessor其中的方法
				registryProcessors.add(registryProcessor);
			}
			else {//TODO:如果自定義的BeanFactoryPostProcessor沒有實現現BeanDefinitionRegistryPostProcessor接口
				regularPostProcessors.add(postProcessor); //TODO:將自定義的BeanFactoryProcessor放到上面定義的集合中
			}
		}

		// 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.
		//TODO:又定義一個集合存放BeanDefinitionRegistryPostProcessor,這個集合存放的是spring內部實現了這個接口的類
		//TODO:放spring內部定義的BeanDefinitionRegistryPostProcessor
		//TODO:每次真正調用的,纔是這個集合中的BeanDefinitionRegistryPostProcessor
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
		//TODO:根據bean的類型獲取bean的名稱,這裏獲取的是BeanDefinitionRegistryPostProcessor類型的
		//TODO:首先調用實現了PriorityOrdered接口的BeanDefinitionRegistryPostProcessor
		//TODO:根據Type獲取對應類型的beanName,這裏纔會獲取出內部定義的ConfigurationClassPostProcessor
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		//TODO:遍歷上面獲得的postProcessorNames,並根據每個beanName獲取對應的beanDefinition,然後放到currentRegistryProcessors中
		//TODO:如果沒有自定義的,則這個時候這裏就一個
		//TODO:同時將遍歷的每一個beanName放到processedBeans中
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				//TODO:將 ConfigurationClassPostProcessor 標記爲已經處理
				processedBeans.add(ppName);
			}
		}
		//TODO:設置排序,不重要
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		//TODO:合併兩個集合,將spring自定義的Processors加入到registryProcessors中,可以看到所謂的currentRegistryProcessors就是一個過渡的
		registryProcessors.addAll(currentRegistryProcessors);
		//TODO:真正的開始調用BeanDefinitionRegistryPostProcessor中的方法
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		//TODO:清空currentRegistryProcessors,這裏就清除了 ConfigurationClassPostProcessor
		currentRegistryProcessors.clear();

		// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
		//TODO:開始調用實現了Ordered接口的BeanDefinitionRegistryPostProcessor類
		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);
			}
		}
		//TODO:和上面的操作一樣,但是這個時候 currentRegistryProcessors 中只會有實現了Ordered接口的BeanDefinitionRegistryPostProcessor
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		currentRegistryProcessors.clear();

		// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
		//TODO:最後,調用其他的BeanDefinitionRegistryPostProcessors,直到沒有更多的BeanDefinitionRegistryPostProcessors實現類
		//TODO:簡單點說這裏就是在掃除剩餘的沒被調用的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);
			currentRegistryProcessors.clear();
		}

		// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
		//TODO:到這裏,調用postProcessBeanFactory(即BeanDefinitionRegistryPostProcessors的父類)的回調方法,這裏面就有針對@Configuration類的增強操作
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	//TODO:如果一個beanFactory不是註冊器,這個應該是一個兼容操作,老版本的spring的BeanFactory是沒有實現Registry接口的
	else {
		// Invoke factory processors registered with the context instance.
		invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}

	//TODO:開始處理 BeanFactoryProcessor 類型的類,並回調指定的方法(就是隻實現了BeanFactoryPorcessor接口的類)
	// 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.
	//TODO:如果已經在processedBeans集合中,這裏不再做處理
	List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();//TODO:存放實現了 PriorityOrdered 接口的 BeanFactoryProcessor
	List<String> orderedPostProcessorNames = new ArrayList<>(); //TODO:存放實現了 Ordered 接口的 BeanFactoryProcessor
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();//TODO:存放沒有實現 Ordered 接口也沒有實現 PriorityOrdered 的 BeanFactoryProcessor
	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);
		}
	}

	//TODO:調用實現了PriorityOrdered接口的BeanFactoryPostProcessor回調方法
	// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	//TODO:調用實現了Ordered接口的 BeanFactoryPostProcessors 回調方法
	// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// Finally, invoke all other BeanFactoryPostProcessors.
	//TODO:最後,處理兩個接口爲沒有實現的正常的 BeanFactoryPostProcessors 回調方法
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	invokeBeanFactoryPostProcessors(nonOrderedPostProcessors, beanFactory);

	// Clear cached merged bean definitions since the post-processors might have
	// modified the original metadata, e.g. replacing placeholders in values...
	beanFactory.clearMetadataCache();
}

這裏說明一下,其中的BeanDefinitionRegistryPostProcessor繼承至BeanFactoryPostProcessor,如下所示

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

	/**
	 * 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;

}

擴展了BeanFactoryPostProcessor中的方法。上述代碼中理清各個list是幹嘛的,但是還有一個重點,就是這個方法invokeBeanDefinitionRegistryPostProcessors;這個方法裏頭的主要操作如下

//PostProcessorRegistrationDelegate 中的第295行
//TODO:調用目標對象的postProcessorBeanDefinitionRegistry方法
private static void invokeBeanDefinitionRegistryPostProcessors(
		Collection<? extends BeanDefinitionRegistryPostProcessor> postProcessors, BeanDefinitionRegistry registry) {

	for (BeanDefinitionRegistryPostProcessor postProcessor : postProcessors) {
        //一個接口的方法,最終會跳到ConfigurationClassPostProcessor的第221行
		postProcessor.postProcessBeanDefinitionRegistry(registry);
	}
}

//TODO:ConfigurationClassPostProcessor的第221行
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);

	//TODO:真正的調用方式, 這裏會跳到ConfigurationClassPostProcessor的第264行
	processConfigBeanDefinitions(registry);
}

真正的BeanFactoryPostProcessor的調用方法

//TODO:BeanFactoryPostProcessor中真正的調用方法,ConfigurationClassPostProcessor中的第264行
//TODO:這個方法就是取出我們自定義的TestConfig,並完成對TestConfig的解析
public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
	List<BeanDefinitionHolder> configCandidates = new ArrayList<>();
    //TODO:到這裏了,candidateNames裏頭就有7個類,分別是6個核心類,一個我們自己定義的TestConfig類
	String[] candidateNames = registry.getBeanDefinitionNames();

	for (String beanName : candidateNames) {
		BeanDefinition beanDef = registry.getBeanDefinition(beanName);
		//TODO:判斷bean是否是核心配置類,bd中configurationClass是否等於full,或者configurationClass是否等於lite
		//TODO:判斷bean是否被處理過,如果bd中的configruationClass屬性等於full或者lite,則表示被處理過
		if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
				ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
			if (logger.isDebugEnabled()) {
				logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
			}
		}
		//TODO:檢查beanDef是否滿足Configuration類的條件,如果滿足,則放入configCandidates集合中
        //TODO:針對checkConfigurationClassCandidate方法,這個方法比較簡單,這裏就不展開說了。如果想看詳情,跳轉到下面關於這個方法的解析
		else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
			configCandidates.add(new BeanDefinitionHolder(beanDef, beanName));
		}
	}

	// Return immediately if no @Configuration classes were found
	if (configCandidates.isEmpty()) {
		return;
	}

	// Sort by previously determined @Order value, if applicable
	configCandidates.sort((bd1, bd2) -> {
		int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
		int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
		return Integer.compare(i1, i2);
	});

	// Detect any custom bean name generation strategy supplied through the enclosing application context
	//TODO:不太重要,命名解析器
	SingletonBeanRegistry sbr = null;
	if (registry instanceof SingletonBeanRegistry) {
		sbr = (SingletonBeanRegistry) registry;
		if (!this.localBeanNameGeneratorSet) {
			BeanNameGenerator generator = (BeanNameGenerator) sbr.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
			if (generator != null) {
				this.componentScanBeanNameGenerator = generator;
				this.importBeanNameGenerator = generator;
			}
		}
	}

	if (this.environment == null) {
		this.environment = new StandardEnvironment();
	}

	// Parse each @Configuration class
	ConfigurationClassParser parser = new ConfigurationClassParser(
			this.metadataReaderFactory, this.problemReporter, this.environment,
			this.resourceLoader, this.componentScanBeanNameGenerator, registry);

	Set<BeanDefinitionHolder> candidates = new LinkedHashSet<>(configCandidates);
	Set<ConfigurationClass> alreadyParsed = new HashSet<>(configCandidates.size());
	do {
		//TODO:解析candidates中的配置類,真正完成掃描
		parser.parse(candidates);
		parser.validate();

		Set<ConfigurationClass> configClasses = new LinkedHashSet<>(parser.getConfigurationClasses());
		configClasses.removeAll(alreadyParsed);

		// Read the model and create bean definitions based on its content
		if (this.reader == null) {
			this.reader = new ConfigurationClassBeanDefinitionReader(
					registry, this.sourceExtractor, this.resourceLoader, this.environment,
					this.importBeanNameGenerator, parser.getImportRegistry());
		}
		this.reader.loadBeanDefinitions(configClasses);
		alreadyParsed.addAll(configClasses);

		candidates.clear();
		if (registry.getBeanDefinitionCount() > candidateNames.length) {
			String[] newCandidateNames = registry.getBeanDefinitionNames();
			Set<String> oldCandidateNames = new HashSet<>(Arrays.asList(candidateNames));
			Set<String> alreadyParsedClasses = new HashSet<>();
			for (ConfigurationClass configurationClass : alreadyParsed) {
				alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
			}
			for (String candidateName : newCandidateNames) {
				if (!oldCandidateNames.contains(candidateName)) {
					BeanDefinition bd = registry.getBeanDefinition(candidateName);
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(bd, this.metadataReaderFactory) &&
							!alreadyParsedClasses.contains(bd.getBeanClassName())) {
						candidates.add(new BeanDefinitionHolder(bd, candidateName));
					}
				}
			}
			candidateNames = newCandidateNames;
		}
	}
	while (!candidates.isEmpty());

	// Register the ImportRegistry as a bean in order to support ImportAware @Configuration classes
	if (sbr != null && !sbr.containsSingleton(IMPORT_REGISTRY_BEAN_NAME)) {
		sbr.registerSingleton(IMPORT_REGISTRY_BEAN_NAME, parser.getImportRegistry());
	}

	if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
		// Clear cache in externally provided MetadataReaderFactory; this is a no-op
		// for a shared cache since it'll be cleared by the ApplicationContext.
		((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
	}
}

關於checkConfigurationClassCandidate方法的補充說明

//TODO:ConfigurationClassUtils 中的82行
//TODO:判斷給定的beanDef是否是一個configuration,判斷這個beanDef是否包含了@Configuration,@Service
public static boolean checkConfigurationClassCandidate(
		BeanDefinition beanDef, MetadataReaderFactory metadataReaderFactory) {

	String className = beanDef.getBeanClassName();
	if (className == null || beanDef.getFactoryMethodName() != null) {
		return false;
	}

	//TODO:獲取beanDefinition的註解元數據信息
	AnnotationMetadata metadata;
	//TODO:判斷是否是註解的bean annotatedBeanDefinition是自定義的bean,如果是spring內部定義的是rootBeanDefinition
	if (beanDef instanceof AnnotatedBeanDefinition &&
			className.equals(((AnnotatedBeanDefinition) beanDef).getMetadata().getClassName())) {
		// Can reuse the pre-parsed metadata from the given BeanDefinition...
		metadata = ((AnnotatedBeanDefinition) beanDef).getMetadata();//TODO:獲取bean上的註解
	}
	//TODO:如果這個類並不是註解的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();
		metadata = new StandardAnnotationMetadata(beanClass, true);//TODO:獲取bean上的註解信息
	}
	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;
		}
	}

	/**
	 * 下述的兩個是if-else if,判斷只會走一個分支,也就是如果只判斷了@Configuration就不會判斷其他的註解,
	 * 之後的Component,ComponentScan,Import,ImportResource之後再進行判斷
	 */

	/**
	 * TODO:如果加了@Configuration註解是一個配置類,
	 * 可以看到isFullConfigurationCandidate方法底層就一行代碼——metadata.isAnnotated(Configuration.class.getName());
	 * 這個就是判斷是否有@Configuration註解
	*/
	if (isFullConfigurationCandidate(metadata)) {
		//TODO:則將beanDefinition中的configurationClass屬性設置爲full
		beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_FULL);
	}
	//TODO:如果是一個lite 的Configuration類(lite是精英的意思),設置beadDefinition中的屬性configurationClass爲lite
	//TODO:判斷是否加了如下的註解,Compnent,ComponentScan,Import,ImportResource
	//		candidateIndicators.add(Component.class.getName());
	//		candidateIndicators.add(ComponentScan.class.getName());
	//		candidateIndicators.add(Import.class.getName());
	//		candidateIndicators.add(ImportResource.class.getName());
	else if (isLiteConfigurationCandidate(metadata)) {
		beanDef.setAttribute(CONFIGURATION_CLASS_ATTRIBUTE, CONFIGURATION_CLASS_LITE);
	}
	else {//TODO:如果兩者都不滿足,則直接返回false
		return false;
	}

	// It's a full or lite configuration candidate... Let's determine the order value, if any.
	//TODO:設置排序 不太重要
	Integer order = getOrder(metadata);
	if (order != null) {
		beanDef.setAttribute(ORDER_ATTRIBUTE, order);
	}

	return true;
}

這裏可以看到,上述方法中的邏輯,如果這個類加上了@Configuration註解,則這個類被標記爲full,如果這個類沒有標記@Configuration,而只是標記了@Component,@ComponentScan,@Import,@ImportResource則這個類被標記爲lite

關於parse中做的一些事兒

目前,根據代碼的梳理,我們已經梳理到了parse方法,這個方法底部就是真正的解析各個@Configuration的類了

/**
 * ConfigurationClassParser中的第163行,這裏並不是很重要
 */
//TODO:解析BeanDefintion
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);
		}
	}

	this.deferredImportSelectorHandler.process();
}

繼續往下走

/**
 * ConfigurationClassParser 中的第200行
 */
protected final void parse(AnnotationMetadata metadata, String beanName) throws IOException {
	processConfigurationClass(new ConfigurationClass(metadata, beanName));
}

/**
 * ConfigurationClassParser 中的第219行
 */
protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
    //判斷當前的configClass是否可以跳過,不重要
	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.
	//TODO:將Configuration類封裝成一個SourceClass
	SourceClass sourceClass = asSourceClass(configClass);
    //do-while操作循環處理configClass
	do {
		//TODO:真正的處理configuration類
		sourceClass = doProcessConfigurationClass(configClass, sourceClass);
	}
	while (sourceClass != null);

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

繼續往下操作

//TODO:處理Configuration的配置類
//.ConfigurationClassParser中的第263行,這裏既是處理@Configuration類的核心邏輯所在。
@Nullable
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass)
		throws IOException {

	//TODO:如果有@Component標籤
	if (configClass.getMetadata().isAnnotated(Component.class.getName())) {
		// Recursively process any member (nested) classes first
		processMemberClasses(configClass, sourceClass);
	}

	// Process any @PropertySource annotations
	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");
		}
	}

	//TODO:處理componentScan註解
	// Process any @ComponentScan annotations
	Set<AnnotationAttributes> componentScans = AnnotationConfigUtils.attributesForRepeatable(
			sourceClass.getMetadata(), ComponentScans.class, ComponentScan.class);
	if (!componentScans.isEmpty() &&
			!this.conditionEvaluator.shouldSkip(sourceClass.getMetadata(), ConfigurationPhase.REGISTER_BEAN)) {
		for (AnnotationAttributes componentScan : componentScans) {
			// The config class is annotated with @ComponentScan -> perform the scan immediately
			Set<BeanDefinitionHolder> scannedBeanDefinitions =
					this.componentScanParser.parse(componentScan, sourceClass.getMetadata().getClassName());
			// Check the set of scanned definitions for any further config classes and parse recursively if needed
			for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
				BeanDefinition bdCand = holder.getBeanDefinition().getOriginatingBeanDefinition();
				if (bdCand == null) {
					bdCand = holder.getBeanDefinition();
				}
				if (ConfigurationClassUtils.checkConfigurationClassCandidate(bdCand, this.metadataReaderFactory)) {
					parse(bdCand.getBeanClassName(), holder.getBeanName());
				}
			}
		}
	}

	//TODO:處理@Import註解
	// Process any @Import annotations
	processImports(configClass, sourceClass, getImports(sourceClass), true);

	//TODO:處理@ImportResource
	// Process any @ImportResource annotations
	AnnotationAttributes importResource =
			AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
	if (importResource != null) {
		String[] resources = importResource.getStringArray("locations");
		Class<? extends BeanDefinitionReader> readerClass = importResource.getClass("reader");
		for (String resource : resources) {
			String resolvedResource = this.environment.resolveRequiredPlaceholders(resource);
			configClass.addImportedResource(resolvedResource, readerClass);
		}
	}

	// Process individual @Bean methods
	Set<MethodMetadata> beanMethods = retrieveBeanMethodMetadata(sourceClass);
	for (MethodMetadata methodMetadata : beanMethods) {
		configClass.addBeanMethod(new BeanMethod(methodMetadata, configClass));
	}

	//TODO:處理接口中默認的方法
	// 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;
}

從代理中的註釋可以看到,其實這個方法就是處理了各個註解標籤,並完成相關的邏輯處理,具體的邏輯處理我們後面再談

小結

總體來看,依舊按照流水線的操作從refresh方法一直梳理下來,如果整體看完這篇博客還是需要毅力的,其實大部分的內容,倒是小弟在閱讀源碼的一個粗略總結,並不詳細,只是梳理了IOC的大致流程,關於ImportSelector和ImportSelector和ImportBeanDefinitionRegistrar的一個區別,可以看下面這篇文章。

關於ImportSelector和ImportBeanDefinitionRegistrar的區別

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章