spring IOC:bean裝配

總結

額。。。寫得並不是很好,不過通過這個來強迫自己去梳理下整個流程,加深印象,也是闊以的

最後,spring的註釋是寫得真的全啊!!!

過程總結:

  1. 項目啓動
  2. 做創建刷新上下文前的各種準備工作
  3. 下面開始裝配bean
  4. 調用BeanDefinitionRegistryPostProcessor加載bean定義
  5. 調用BeanFactoryPostProcessor修改替換bean定義裏面的屬性值(${…}})
  6. 遍歷加載的定義,開始裝配bean
  7. 如果是單例模式先查緩存,緩存直接就返回
  8. 判斷是不是正在構建的Prototype bean,是就直接報異常
  9. 如果父BeanFactory不爲空,並且沒有bean定義,則調用父BeanFactory獲取bean
  10. 標記bean已經構建
  11. 檢查bean是否abstract類,是直接報錯
  12. 如果有@DependsOn,先構建被依賴的bean,並且記錄依賴關係
  13. 開始bean構建
    13.1. 處理@Lookup註解
    13.2. 調用InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
    13.3. 通過構造函數創建對象
    13.4. 調用MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition接口
    13.5. 初始化bean屬性:
    13.5.1. 調用InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation方法
    13.5.2.給@Autowired屬性注入對象
    13.5.3. 調用InstantiationAwareBeanPostProcessor#postProcessPropertyValues方法
    13.6. 初始化bean:
    13.6.1 調用BeanPostProcessor#postProcessBeforeInitialization方法(@PostConstruct),
    13.6.2 調用afterPropertiesSet方法或者指定的init method,
    13.6.3 執行BeanPostProcessor#postProcessAfterInitialization方法
    13.6.4 註冊爲DisposableBean
  14. 如果需要類型轉換的則進行轉換

涉及spring的功能:

  • @Conditional:是在bean定義加載階段進行判斷
  • @Bean:註解了@Bean的方法,也是在bean定義階段被作爲bean處理,加載到定義中
  • @PriorityOrdered:比@Oordered先執行
  • 單例模式:第一次構建後會放入到緩存中,後續都是從緩存中取
  • @DependsOn:bean構建前先構建@DependsOn指定的對象,並且最後銷燬的時候,依賴方會先被銷燬
  • 構造函數:調用構造函數時,屬性還沒被初始化,除非指定了構造參數
  • InitializingBean:在bean的屬性配置完成後纔會調用

過程

總流程:

SpringApplication#run
SpringApplication#createAndRefreshContext
SpringApplication#refresh
AbstractApplicationContext#refresh

下面是bean加載流程,這次主要關注3:bean定義的加載和7:構建bean,這兩個主要流程

  1. 上下文準備
  2. beanFactory的配置
  3. 調用所有BeanDefinitionRegistryPostProcessor#postProcessBeanDefinitionRegistry和BeanFactoryPostProcessor#postProcessBeanDefinitionRegistry方法:invokeBeanFactoryPostProcessors(beanFactory)
  4. 初始化MessageSource
  5. 初始化事件廣播器
  6. 註冊BeanPostProcessor(沒有調用):registerBeanPostProcessors(beanFactory)
  7. 構建bean並放入容器中:finishBeanFactoryInitialization(beanFactory)
  8. 初始化並調用LifecycleProcessor的onRefresh方法,發送事件
@Override
	public void refresh() throws BeansException, IllegalStateException {
		synchronized (this.startupShutdownMonitor) {
			// Prepare this context for refreshing.
			prepareRefresh();

			// Tell the subclass to refresh the internal bean factory.
			// 獲取BeanFactory
			ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

			// Prepare the bean factory for use in this context.
			// 配置BeanFactory
			prepareBeanFactory(beanFactory);

			try {
				// Allows post-processing of the bean factory in context subclasses.
				postProcessBeanFactory(beanFactory);

				// Invoke factory processors registered as beans in the context.
				// 調用BeanFactoryPostProcessor,
				invokeBeanFactoryPostProcessors(beanFactory);

				// Register bean processors that intercept bean creation.
				// 註冊BeanPostProcessor(沒有調用)
				registerBeanPostProcessors(beanFactory);

				// Initialize message source for this context.
				initMessageSource();

				// Initialize event multicaster for this context.
				// 初始化事件廣播器
				initApplicationEventMulticaster();

				// Initialize other special beans in specific context subclasses.
				onRefresh();

				// Check for listener beans and register them.
				// 註冊監聽器ApplicationListener
				registerListeners();

				// Instantiate all remaining (non-lazy-init) singletons.
				// 構建bean並放入容器中
				finishBeanFactoryInitialization(beanFactory);

				// Last step: publish corresponding event.
				// 初始化並調用LifecycleProcessor的onRefresh方法,發送事件
				finishRefresh();
			}

			catch (BeansException ex) {
				if (logger.isWarnEnabled()) {
					logger.warn("Exception encountered during context initialization - " +
							"cancelling refresh attempt: " + ex);
				}

				// Destroy already created singletons to avoid dangling resources.
				destroyBeans();

				// Reset 'active' flag.
				cancelRefresh(ex);

				// Propagate exception to caller.
				throw ex;
			}

			finally {
				// Reset common introspection caches in Spring's core, since we
				// might not ever need metadata for singleton beans anymore...
				resetCommonCaches();
			}
		}
	}

bean定義:BeanDefinition

先來看看bean定義是什麼

bean定義用來描述bean,後續bean構建的時候就是根據bean定義來構建,下面是bean定義的一個結構圖,
bean定義結構圖
bean定義裏面的內容,大概內容看方法名字基本就知道了,包含了諸如:類型、構建工廠、scope、構建方法、屬性等的信息

BeanDefinition屬性
AnnotatedBeanDefinition在BeanDefinition基礎上擴展了對註解相關信息的支持
AnnotatedBeanDefinition

調用所有BeanFactoryPostProcessor(包含BeanDefinitionRegistryPostProcessor)

BeanFactoryPostProcessor實際上也分爲兩類:BeanFactoryPostProcessor和BeanFactoryPostProcessor的子類BeanDefinitionRegistryPostProcessor

過程:

AbstractApplicationContext#invokeBeanFactoryPostProcessors
PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

額。。。這個方法看着很複雜,但其實總體上可以劃分爲兩塊:執行BeanDefinitionRegistryPostProcessor、執行BeanFactoryPostProcessor,下面看下具體執行流程

  1. 如果傳入的beanFactory是BeanDefinitionRegistry的實例
    1.1 遍歷參數傳入的beanFactoryPostProcessors,如果是BeanFactoryPostProcessor先放到列表中,如果是BeanDefinitionRegistryPostProcessor,直接執行它的postProcessBeanDefinitionRegistry方法
    1.2 通過beanFactory#getBeanNamesForType方法查出BeanDefinitionRegistryPostProcessor的實現對象,然後分爲三組:a.實現了PriorityOrdered接口的 b.實現了Ordered接口 c.其他
    1.3 對a組排序,然後依次postProcessBeanDefinitionRegistry方法
    1.4 對b組排序,然後依次postProcessBeanDefinitionRegistry方法
    1.5 然後依次執行c組的postProcessBeanDefinitionRegistry方法
    1.6 最後再執行在1.1分出來的BeanFactoryPostProcessor的方法
  2. 如果傳入的beanFactory不是BeanDefinitionRegistry的實例,則直接執行傳參beanFactoryPostProcessors的BeanFactoryPostProcessor#postProcessBeanFactory方法
  3. 通過beanFactory#getBeanNamesForType方法查出BeanFactoryPostProcessor的實現對象,然後分爲三組:a.實現了PriorityOrdered接口的 b.實現了Ordered接口 c.其他
    3.1 對a組排序,然後依次postProcessBeanFactory方法
    3.2 對b組排序,然後依次postProcessBeanFactory方法
    3.3 然後依次執行c組的postProcessBeanFactory方法

P.S.這塊看起來比較複雜,感覺是因爲兩塊的代碼風格寫起來不一致,第一塊的3組的獲取是調用了3次getBeanNamesForType方法,然後每次根據不同條件來取出對應的bean,導致代碼很多且複雜;第二塊,是調一次接口,一次循環直接分成3組,後面一次執行,這樣看起來更舒服,更優雅

public static void invokeBeanFactoryPostProcessors(
			ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

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

	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
		List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
				new LinkedList<BeanDefinitionRegistryPostProcessor>();

		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryPostProcessor =
						(BeanDefinitionRegistryPostProcessor) postProcessor;
				registryPostProcessor.postProcessBeanDefinitionRegistry(registry);
				registryPostProcessors.add(registryPostProcessor);
			}
			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.
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
		List<BeanDefinitionRegistryPostProcessor> priorityOrderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
		registryPostProcessors.addAll(priorityOrderedPostProcessors);
		invokeBeanDefinitionRegistryPostProcessors(priorityOrderedPostProcessors, registry);

		// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
		postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		List<BeanDefinitionRegistryPostProcessor> orderedPostProcessors = new ArrayList<BeanDefinitionRegistryPostProcessor>();
		for (String ppName : postProcessorNames) {
			if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
				orderedPostProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(beanFactory, orderedPostProcessors);
		registryPostProcessors.addAll(orderedPostProcessors);
		invokeBeanDefinitionRegistryPostProcessors(orderedPostProcessors, registry);

		// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
		boolean reiterate = true;
		while (reiterate) {
			reiterate = false;
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				if (!processedBeans.contains(ppName)) {
					BeanDefinitionRegistryPostProcessor pp = beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class);
					registryPostProcessors.add(pp);
					processedBeans.add(ppName);
					pp.postProcessBeanDefinitionRegistry(registry);
					reiterate = true;
				}
			}
		}

		// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
		invokeBeanFactoryPostProcessors(registryPostProcessors, 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<BeanFactoryPostProcessor>();
	List<String> orderedPostProcessorNames = new ArrayList<String>();
	List<String> nonOrderedPostProcessorNames = new ArrayList<String>();
	for (String ppName : postProcessorNames) {
		if (processedBeans.contains(ppName)) {
			// skip - already processed in first phase above
		}
		else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
	sortPostProcessors(beanFactory, priorityOrderedPostProcessors);
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);

	// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	sortPostProcessors(beanFactory, orderedPostProcessors);
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);

	// Finally, invoke all other BeanFactoryPostProcessors.
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<BeanFactoryPostProcessor>();
	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:

按執行順序,先來看下BeanDefinitionRegistryPostProcessor

定義:

BeanDefinitionRegistryPostProcessor是屬於BeanFactoryPostProcessor的子類,會在BeanFactoryPostProcessor#postProcessBeanFactory執行前執行postProcessBeanDefinitionRegistry方法(從上面的執行流程可以看出來),只加載定義不構建bean,並且在BeanFactoryPostProcessor基礎上,可以註冊更多的bean定義信息,這些定義信息能定義BeanFactoryPostProcessor(渣翻。。。)

其實整個看來,就是負責bean定義的加載

/**
 * Extension to the standard {@link BeanFactoryPostProcessor} SPI, allowing for
 * the registration of further bean definitions <i>before</i> regular
 * BeanFactoryPostProcessor detection kicks in. In particular,
 * BeanDefinitionRegistryPostProcessor may register further bean definitions
 * which in turn define BeanFactoryPostProcessor instances.
 *
 * @author Juergen Hoeller
 * @since 3.0.1
 * @see org.springframework.context.annotation.ConfigurationClassPostProcessor
 */
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;

}

過程:

先來看下有多少實現類
在這裏插入圖片描述
spring自己的實現類,其實只有2個:ConfigurationWarningsPostProcessor和ConfigurationClassPostProcessor,而且ConfigurationWarningsPostProcessor只是用來打印warning信息,因此主要來看下這個ConfigurationClassPostProcessor

而ConfigurationClassPostProcessor就是負責定義加載了

ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry
ConfigurationClassPostProcessor#processConfigBeanDefinitions
流程總結爲:

  1. 取出當前所有已註冊的bean定義:SpringApplication#createApplicationContext創建時註冊的註解相關的PostProcessor,源定義,還有ConfigurationClassPostProcessor#postProcessBeanDefinitionRegistry註冊的2個PostProcessors
    在這裏插入圖片描述
  2. 從已註冊的bean定義中取出配置類型的bean定義,就是包含有以下註解的:@Configuration,@Component,@ComponentScan,@Import,@ImportResource
  3. 排序
  4. 解析這些配置bean,會根據@Conditional條件判斷是否跳過,根據配置信息取出所有需要加載的bean,例如:配置bean上有@ComponentScan註解,他就會去取出指定包下的所有bean;有@ImportResource註解,就會去讀對應的配置文件取出裏面配置的bean(詳細過程後面下面再講)
  5. 校驗:Configuration不能有子類,@Bean註解的方法不能重載
  6. 加載4中取出的bean的定義
  7. 再從新加載的這批bean定義中篩選出還沒有解析的配置類型的bean,然後在重複4,5,6的動作,直至所有配置類型的bean都被解析
  8. 最後,把parser.getImportRegistry()註冊上去,不是很瞭解這個是啥

至此,BeanDefinitionRegistryPostProcessor調用已經完成

public void processConfigBeanDefinitions(BeanDefinitionRegistry registry) {
		List<BeanDefinitionHolder> configCandidates = new ArrayList<BeanDefinitionHolder>();
	// 取出所有已註冊的bean定義
	String[] candidateNames = registry.getBeanDefinitionNames();
	// 篩選出配置類型的bean定義
	for (String beanName : candidateNames) {
		BeanDefinition beanDef = registry.getBeanDefinition(beanName);
		if (ConfigurationClassUtils.isFullConfigurationClass(beanDef) ||
				ConfigurationClassUtils.isLiteConfigurationClass(beanDef)) {
			// 如果這兩個字段已被設置,證明這個bean定義已被處理過
			if (logger.isDebugEnabled()) {
				logger.debug("Bean definition has already been processed as a configuration class: " + beanDef);
			}
		}
		else if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory)) {
			// 判斷依據:是否包含有以下註解的:@Configuration,@Component,@ComponentScan,@Import,@ImportResource
			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
	Collections.sort(configCandidates, new Comparator<BeanDefinitionHolder>() {
		@Override
		public int compare(BeanDefinitionHolder bd1, BeanDefinitionHolder bd2) {
			int i1 = ConfigurationClassUtils.getOrder(bd1.getBeanDefinition());
			int i2 = ConfigurationClassUtils.getOrder(bd2.getBeanDefinition());
			return (i1 < i2) ? -1 : (i1 > i2) ? 1 : 0;
		}
	});

	// Detect any custom bean name generation strategy supplied through the enclosing application context
	// bean名字生成器選擇
	SingletonBeanRegistry singletonRegistry = null;
	if (registry instanceof SingletonBeanRegistry) {
		singletonRegistry = (SingletonBeanRegistry) registry;
		if (!this.localBeanNameGeneratorSet && singletonRegistry.containsSingleton(CONFIGURATION_BEAN_NAME_GENERATOR)) {
			BeanNameGenerator generator = (BeanNameGenerator) singletonRegistry.getSingleton(CONFIGURATION_BEAN_NAME_GENERATOR);
			this.componentScanBeanNameGenerator = generator;
			this.importBeanNameGenerator = generator;
		}
	}

	// Parse each @Configuration class
	// 構建配置bean的解析器
	ConfigurationClassParser parser = new ConfigurationClassParser(
			this.metadataReaderFactory, this.problemReporter, this.environment,
			this.resourceLoader, this.componentScanBeanNameGenerator, registry);

	Set<BeanDefinitionHolder> candidates = new LinkedHashSet<BeanDefinitionHolder>(configCandidates);
	Set<ConfigurationClass> alreadyParsed = new HashSet<ConfigurationClass>(configCandidates.size());
	do {
		// 根據配置信息取出所有需要加載的bean
		parser.parse(candidates);
		// 校驗:Configuration不能有子類,@Bean註解的方法不能重載
		parser.validate();

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

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

		candidates.clear();
		// 從新加載的bean中找出配置類
		if (registry.getBeanDefinitionCount() > candidateNames.length) {
			String[] newCandidateNames = registry.getBeanDefinitionNames();
			Set<String> oldCandidateNames = new HashSet<String>(Arrays.asList(candidateNames));
			Set<String> alreadyParsedClasses = new HashSet<String>();
			for (ConfigurationClass configurationClass : alreadyParsed) {
				alreadyParsedClasses.add(configurationClass.getMetadata().getClassName());
			}
			for (String candidateName : newCandidateNames) {
				if (!oldCandidateNames.contains(candidateName)) {
					BeanDefinition beanDef = registry.getBeanDefinition(candidateName);
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(beanDef, this.metadataReaderFactory) &&
							!alreadyParsedClasses.contains(beanDef.getBeanClassName())) {
						candidates.add(new BeanDefinitionHolder(beanDef, candidateName));
					}
				}
			}
			candidateNames = newCandidateNames;
		}
	}
	while (!candidates.isEmpty());

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

	if (this.metadataReaderFactory instanceof CachingMetadataReaderFactory) {
		((CachingMetadataReaderFactory) this.metadataReaderFactory).clearCache();
	}
}

配置類的解析:

ConfigurationClassParser#parse
ConfigurationClassParser#processConfigurationClass

protected void processConfigurationClass(ConfigurationClass configClass) throws IOException {
	// 根據@Conditional註解條件,決定是否需要加載
	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);
			for (Iterator<ConfigurationClass> it = this.knownSuperclasses.values().iterator(); it.hasNext(); ) {
				if (configClass.equals(it.next())) {
					it.remove();
				}
			}
		}
	}

	// Recursively process the configuration class and its superclass hierarchy.
	// 包裝成SourceClass 
	SourceClass sourceClass = asSourceClass(configClass);
	do {
		sourceClass = doProcessConfigurationClass(configClass, sourceClass);
	}
	while (sourceClass != null);

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

ConfigurationClassParser#doProcessConfigurationClass
主要解析的部分,流程可以分爲:

  1. 檢查是否存在內部類也是配置類,存在則回到上個調用方法開始解析
  2. 處理@PropertySource註解
  3. 處理@ComponentScan
  4. 處理@Import
  5. 處理@ImportResource
  6. @Bean的方法
  7. 處理接口上帶有@Bean註解的方法
  8. 處理父類,從1開始一遍
protected final SourceClass doProcessConfigurationClass(ConfigurationClass configClass, SourceClass sourceClass) throws IOException {
		// 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.warn("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 necessary
				for (BeanDefinitionHolder holder : scannedBeanDefinitions) {
					if (ConfigurationClassUtils.checkConfigurationClassCandidate(holder.getBeanDefinition(), this.metadataReaderFactory)) {
						parse(holder.getBeanDefinition().getBeanClassName(), holder.getBeanName());
					}
				}
			}
		}

		// Process any @Import annotations
		processImports(configClass, sourceClass, getImports(sourceClass), true);

		// Process any @ImportResource annotations
		if (sourceClass.getMetadata().isAnnotated(ImportResource.class.getName())) {
			AnnotationAttributes importResource =
					AnnotationConfigUtils.attributesFor(sourceClass.getMetadata(), ImportResource.class);
			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 = sourceClass.getMetadata().getAnnotatedMethods(Bean.class.getName());
		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.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;
	}

BeanFactoryPostProcessor:

先看下注釋,主要有兩個功能:

  • 修改bean定義:目前來看主要是其子類BeanDefinitionRegistryPostProcessor完成了這個功能
  • 修改bean屬性:通過讀取配置文件修改屬性值,然後提到了PropertyResourceConfigurer這個類,專門用於解決這個配置的問題

最後說到了注意事項,只能操作bean定義,但是不準實例化對象,否則會導致意外的問題

定義在前面的時候已經加載了,這邊基本是對屬性值的一個修改

/**
 * Allows for custom modification of an application context's bean definitions,
 * adapting the bean property values of the context's underlying bean factory.
 *
 * <p>Application contexts can auto-detect BeanFactoryPostProcessor beans in
 * their bean definitions and apply them before any other beans get created.
 *
 * <p>Useful for custom config files targeted at system administrators that
 * override bean properties configured in the application context.
 *
 * <p>See PropertyResourceConfigurer and its concrete implementations
 * for out-of-the-box solutions that address such configuration needs.
 *
 * <p>A BeanFactoryPostProcessor may interact with and modify bean
 * definitions, but never bean instances. Doing so may cause premature bean
 * instantiation, violating the container and causing unintended side-effects.
 * If bean instance interaction is required, consider implementing
 * {@link BeanPostProcessor} instead.
 *
 * @author Juergen Hoeller
 * @since 06.07.2003
 * @see BeanPostProcessor
 * @see PropertyResourceConfigurer
 */
public interface BeanFactoryPostProcessor {

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

}

註冊BeanPostProcessor

PostProcessorRegistrationDelegate#registerBeanPostProcessors
這塊其實跟上面調用BeanFactoryPostProcessor類似,也是通過beanFactory#getBeanNamesForType方法查出所有BeanPostProcessor對象,然後分成3組:a.實現了PriorityOrdered接口的 b.實現了Ordered接口 c.其他。不同的是上面的是直接調用,這裏是添加到beanFactory的BeanPostProcessor列表裏面,供後續調用

構建bean

總流程:

  1. 如果是單例模式先查緩存,緩存有就返回
  2. 判斷是不是正在構建的Prototype bean,是就直接報異常
  3. 如果父BeanFactory不爲空,並且沒有bean定義,則調用父BeanFactory獲取bean
  4. 標記bean已經構建
  5. 檢查bean是否abstract類,是直接報錯
  6. 如果有@DependsOn,先構建被依賴的bean,並且記錄依賴關係
  7. 根據scope分3種情況執行
    7.1 單例模式的構建
    7.1.1. 處理@Lookup註解
    7.1.2. 調用InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation
    7.1.3. 通過構造函數創建對象
    7.1.4. 調用MergedBeanDefinitionPostProcessor#postProcessMergedBeanDefinition接口
    7.1.5. 初始化bean屬性:調用InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation方法,給@Autowired屬性注入對象,調用InstantiationAwareBeanPostProcessor#postProcessPropertyValues方法
    7.1.6. 初始化bean:調用BeanPostProcessor#postProcessBeforeInitialization方法,調用afterPropertiesSet方法或者指定的init method,執行BeanPostProcessor#postProcessAfterInitialization方法
    7.2 原型模式的構建
    7.3 其他構建
  8. 如果需要類型轉換的則進行轉換

AbstractApplicationContext#finishBeanFactoryInitialization
DefaultListableBeanFactory#preInstantiateSingletons

@Override
	public void preInstantiateSingletons() throws BeansException {
		if (this.logger.isDebugEnabled()) {
			this.logger.debug("Pre-instantiating singletons in " + this);
		}

		// Iterate over a copy to allow for init methods which in turn register new bean definitions.
		// While this may not be part of the regular factory bootstrap, it does otherwise work fine.
		// 前面加載的bean定義
		List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

		// Trigger initialization of all non-lazy singleton beans...
		for (String beanName : beanNames) {
			RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
			// 不是虛類 and 是單例模式 and 不是延遲加載
			if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
				if (isFactoryBean(beanName)) {
					// 如果實現了FactoryBean接口,再判斷是否是現在就構建
					final FactoryBean<?> factory = (FactoryBean<?>) getBean(FACTORY_BEAN_PREFIX + beanName);
					boolean isEagerInit;
					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
						isEagerInit = AccessController.doPrivileged(new PrivilegedAction<Boolean>() {
							@Override
							public Boolean run() {
								return ((SmartFactoryBean<?>) factory).isEagerInit();
							}
						}, getAccessControlContext());
					}
					else {
						isEagerInit = (factory instanceof SmartFactoryBean &&
								((SmartFactoryBean<?>) factory).isEagerInit());
					}
					if (isEagerInit) {
						getBean(beanName);
					}
				}
				else {
					// 非FactoryBean直接構建
					getBean(beanName);
				}
			}
		}

		// Trigger post-initialization callback for all applicable beans...
		// 如果實現了SmartInitializingSingleton接口,調用它的afterSingletonsInstantiated方法
		for (String beanName : beanNames) {
			Object singletonInstance = getSingleton(beanName);
			if (singletonInstance instanceof SmartInitializingSingleton) {
				final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
				if (System.getSecurityManager() != null) {
					AccessController.doPrivileged(new PrivilegedAction<Object>() {
						@Override
						public Object run() {
							smartSingleton.afterSingletonsInstantiated();
							return null;
						}
					}, getAccessControlContext());
				}
				else {
					smartSingleton.afterSingletonsInstantiated();
				}
			}
		}
	}

下面來看具體的構建過程
AbstractBeanFactory#getBean
AbstractBeanFactory#doGetBean

不同模式構建其實都一樣,都是調用AbstractAutowireCapableBeanFactory#createBean構建,只是觸發的接口調用不同

protected <T> T doGetBean(
			final String name, final Class<T> requiredType, final Object[] args, boolean typeCheckOnly)
			throws BeansException {

		final String beanName = transformedBeanName(name);
		Object bean;

		// Eagerly check singleton cache for manually registered singletons.
		// 單例模式會先從緩存取
		Object sharedInstance = getSingleton(beanName);
		if (sharedInstance != null && args == null) {
			if (logger.isDebugEnabled()) {
				if (isSingletonCurrentlyInCreation(beanName)) {
					logger.debug("Returning eagerly cached instance of singleton bean '" + beanName +
							"' that is not fully initialized yet - a consequence of a circular reference");
				}
				else {
					logger.debug("Returning cached instance of singleton bean '" + beanName + "'");
				}
			}
			bean = getObjectForBeanInstance(sharedInstance, name, beanName, null);
		}

		else {
			// Fail if we're already creating this bean instance:
			// We're assumably within a circular reference.
			// 判斷是不是正在構建的Prototype bean
			if (isPrototypeCurrentlyInCreation(beanName)) {
				throw new BeanCurrentlyInCreationException(beanName);
			}

			// Check if bean definition exists in this factory.
			// 如果查不到bean定義,調用父BeanFactory去獲取bean
			BeanFactory parentBeanFactory = getParentBeanFactory();
			if (parentBeanFactory != null && !containsBeanDefinition(beanName)) {
				// Not found -> check parent.
				String nameToLookup = originalBeanName(name);
				if (args != null) {
					// Delegation to parent with explicit args.
					return (T) parentBeanFactory.getBean(nameToLookup, args);
				}
				else {
					// No args -> delegate to standard getBean method.
					return parentBeanFactory.getBean(nameToLookup, requiredType);
				}
			}

			// 如果是要構建bean的,把bean標誌已經創建(加入到alreadyCreated)
			if (!typeCheckOnly) {
				markBeanAsCreated(beanName);
			}

			try {
				final RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
				checkMergedBeanDefinition(mbd, beanName, args);

				// Guarantee initialization of beans that the current bean depends on.
				// 如果有@DependsOn註解,先構建依賴的bean
				String[] dependsOn = mbd.getDependsOn();
				if (dependsOn != null) {
					for (String dependsOnBean : dependsOn) {
						// 如果有循環依賴,直接報錯
						if (isDependent(beanName, dependsOnBean)) {
							throw new BeanCreationException(mbd.getResourceDescription(), beanName,
									"Circular depends-on relationship between '" + beanName + "' and '" + dependsOnBean + "'");
						}
						// 標記下這個bean依賴了哪些bean,後續銷燬的時候,先銷燬依賴方
						registerDependentBean(dependsOnBean, beanName);
						// 構建bean
						getBean(dependsOnBean);
					}
				}

				// Create bean instance.
				// 根據scope,分3中情況執行
				if (mbd.isSingleton()) {
					// 單例模式
					sharedInstance = getSingleton(beanName, new ObjectFactory<Object>() {
						@Override
						public Object getObject() throws BeansException {
							try {
								return createBean(beanName, mbd, args);
							}
							catch (BeansException ex) {
								// Explicitly remove instance from singleton cache: It might have been put there
								// eagerly by the creation process, to allow for circular reference resolution.
								// Also remove any beans that received a temporary reference to the bean.
								destroySingleton(beanName);
								throw ex;
							}
						}
					});
					bean = getObjectForBeanInstance(sharedInstance, name, beanName, mbd);
				}

				else if (mbd.isPrototype()) {
					// prototype模式
					// It's a prototype -> create a new instance.
					Object prototypeInstance = null;
					try {
						beforePrototypeCreation(beanName);
						prototypeInstance = createBean(beanName, mbd, args);
					}
					finally {
						afterPrototypeCreation(beanName);
					}
					bean = getObjectForBeanInstance(prototypeInstance, name, beanName, mbd);
				}

				else {
					// 其他模式
					String scopeName = mbd.getScope();
					final Scope scope = this.scopes.get(scopeName);
					if (scope == null) {
						throw new IllegalStateException("No Scope registered for scope name '" + scopeName + "'");
					}
					try {
						Object scopedInstance = scope.get(beanName, new ObjectFactory<Object>() {
							@Override
							public Object getObject() throws BeansException {
								beforePrototypeCreation(beanName);
								try {
									return createBean(beanName, mbd, args);
								}
								finally {
									afterPrototypeCreation(beanName);
								}
							}
						});
						bean = getObjectForBeanInstance(scopedInstance, name, beanName, mbd);
					}
					catch (IllegalStateException ex) {
						throw new BeanCreationException(beanName,
								"Scope '" + scopeName + "' is not active for the current thread; consider " +
								"defining a scoped proxy for this bean if you intend to refer to it from a singleton",
								ex);
					}
				}
			}
			catch (BeansException ex) {
				cleanupAfterBeanCreationFailure(beanName);
				throw ex;
			}
		}

		// Check if required type matches the type of the actual bean instance.
		if (requiredType != null && bean != null && !requiredType.isAssignableFrom(bean.getClass())) {
			try {
				return getTypeConverter().convertIfNecessary(bean, requiredType);
			}
			catch (TypeMismatchException ex) {
				if (logger.isDebugEnabled()) {
					logger.debug("Failed to convert bean '" + name + "' to required type [" +
							ClassUtils.getQualifiedName(requiredType) + "]", ex);
				}
				throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
			}
		}
		return (T) bean;
	}

下面就看下單例模式爲例

DefaultSingletonBeanRegistry#getSingleton
AbstractAutowireCapableBeanFactory#createBean

protected Object createBean(String beanName, RootBeanDefinition mbd, Object[] args) throws BeanCreationException {
	if (logger.isDebugEnabled()) {
		logger.debug("Creating instance of bean '" + beanName + "'");
	}
	RootBeanDefinition mbdToUse = mbd;

	// Make sure bean class is actually resolved at this point, and
	// clone the bean definition in case of a dynamically resolved Class
	// which cannot be stored in the shared merged bean definition.
	// 獲取bean類型,並複製bean定義,
	Class<?> resolvedClass = resolveBeanClass(mbd, beanName);
	if (resolvedClass != null && !mbd.hasBeanClass() && mbd.getBeanClassName() != null) {
		mbdToUse = new RootBeanDefinition(mbd);
		mbdToUse.setBeanClass(resolvedClass);
	}

	// Prepare method overrides.
	// 處理有方法添加了@Lookup註解的類
	try {
		mbdToUse.prepareMethodOverrides();
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanDefinitionStoreException(mbdToUse.getResourceDescription(),
				beanName, "Validation of method overrides failed", ex);
	}

	// 調用InstantiationAwareBeanPostProcessor#postProcessBeforeInstantiation,和#postProcessAfterInitialization(前面返回不爲空的話)
	// 看了下,還沒有實現類來通過這個接口返回對象的,因爲到這,bean還沒初始化,如果這裏創建代理的話,要做的事情太多
	try {
		// Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
		Object bean = resolveBeforeInstantiation(beanName, mbdToUse);
		if (bean != null) {
			return bean;
		}
	}
	catch (Throwable ex) {
		throw new BeanCreationException(mbdToUse.getResourceDescription(), beanName,
				"BeanPostProcessor before instantiation of bean failed", ex);
	}

	Object beanInstance = doCreateBean(beanName, mbdToUse, args);
	if (logger.isDebugEnabled()) {
		logger.debug("Finished creating instance of bean '" + beanName + "'");
	}
	return beanInstance;
}

AbstractAutowireCapableBeanFactory#doCreateBean

protected Object doCreateBean(final String beanName, final RootBeanDefinition mbd, final Object[] args) {
	// Instantiate the bean.
	BeanWrapper instanceWrapper = null;
	if (mbd.isSingleton()) {
		instanceWrapper = this.factoryBeanInstanceCache.remove(beanName);
	}
	// 創建bean對象,只是調用了構造函數
	if (instanceWrapper == null) {
		instanceWrapper = createBeanInstance(beanName, mbd, args);
	}
	final Object bean = (instanceWrapper != null ? instanceWrapper.getWrappedInstance() : null);
	Class<?> beanType = (instanceWrapper != null ? instanceWrapper.getWrappedClass() : null);

	// Allow post-processors to modify the merged bean definition.
	// 調用MergedBeanDefinitionPostProcessor接口
	synchronized (mbd.postProcessingLock) {
		if (!mbd.postProcessed) {
			applyMergedBeanDefinitionPostProcessors(mbd, beanType, beanName);
			mbd.postProcessed = true;
		}
	}

	// Eagerly cache singletons to be able to resolve circular references
	// even when triggered by lifecycle interfaces like BeanFactoryAware.
	boolean earlySingletonExposure = (mbd.isSingleton() && this.allowCircularReferences &&
			isSingletonCurrentlyInCreation(beanName));
	if (earlySingletonExposure) {
		if (logger.isDebugEnabled()) {
			logger.debug("Eagerly caching bean '" + beanName +
					"' to allow for resolving potential circular references");
		}
		addSingletonFactory(beanName, new ObjectFactory<Object>() {
			@Override
			public Object getObject() throws BeansException {
				return getEarlyBeanReference(beanName, mbd, bean);
			}
		});
	}

	// Initialize the bean instance.
	Object exposedObject = bean;
	try {
		// 初始化bean屬性
		populateBean(beanName, mbd, instanceWrapper);
		if (exposedObject != null) {
			// 初始化bean
			exposedObject = initializeBean(beanName, exposedObject, mbd);
		}
	}
	catch (Throwable ex) {
		if (ex instanceof BeanCreationException && beanName.equals(((BeanCreationException) ex).getBeanName())) {
			throw (BeanCreationException) ex;
		}
		else {
			throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Initialization of bean failed", ex);
		}
	}

	if (earlySingletonExposure) {
		Object earlySingletonReference = getSingleton(beanName, false);
		if (earlySingletonReference != null) {
			if (exposedObject == bean) {
				exposedObject = earlySingletonReference;
			}
			else if (!this.allowRawInjectionDespiteWrapping && hasDependentBean(beanName)) {
				String[] dependentBeans = getDependentBeans(beanName);
				Set<String> actualDependentBeans = new LinkedHashSet<String>(dependentBeans.length);
				for (String dependentBean : dependentBeans) {
					if (!removeSingletonIfCreatedForTypeCheckOnly(dependentBean)) {
						actualDependentBeans.add(dependentBean);
					}
				}
				if (!actualDependentBeans.isEmpty()) {
					throw new BeanCurrentlyInCreationException(beanName,
							"Bean with name '" + beanName + "' has been injected into other beans [" +
							StringUtils.collectionToCommaDelimitedString(actualDependentBeans) +
							"] in its raw version as part of a circular reference, but has eventually been " +
							"wrapped. This means that said other beans do not use the final version of the " +
							"bean. This is often the result of over-eager type matching - consider using " +
							"'getBeanNamesOfType' with the 'allowEagerInit' flag turned off, for example.");
				}
			}
		}
	}

	// Register bean as disposable.
	// 註冊銷燬方法
	try {
		registerDisposableBeanIfNecessary(beanName, bean, mbd);
	}
	catch (BeanDefinitionValidationException ex) {
		throw new BeanCreationException(mbd.getResourceDescription(), beanName, "Invalid destruction signature", ex);
	}

	return exposedObject;
}

主要看下bean的初始化那塊吧:

初始化bean的屬性

AbstractAutowireCapableBeanFactory#populateBean

protected void populateBean(String beanName, RootBeanDefinition mbd, BeanWrapper bw) {
		PropertyValues pvs = mbd.getPropertyValues();

	if (bw == null) {
		if (!pvs.isEmpty()) {
			throw new BeanCreationException(
					mbd.getResourceDescription(), beanName, "Cannot apply property values to null instance");
		}
		else {
			// Skip property population phase for null instance.
			return;
		}
	}

	// Give any InstantiationAwareBeanPostProcessors the opportunity to modify the
	// state of the bean before properties are set. This can be used, for example,
	// to support styles of field injection.
	boolean continueWithPropertyPopulation = true;

	// 調用InstantiationAwareBeanPostProcessor#postProcessAfterInstantiation方法
	if (!mbd.isSynthetic() && hasInstantiationAwareBeanPostProcessors()) {
		for (BeanPostProcessor bp : getBeanPostProcessors()) {
			if (bp instanceof InstantiationAwareBeanPostProcessor) {
				InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
				if (!ibp.postProcessAfterInstantiation(bw.getWrappedInstance(), beanName)) {
					continueWithPropertyPopulation = false;
					break;
				}
			}
		}
	}

	if (!continueWithPropertyPopulation) {
		return;
	}

	// 給@Autowired屬性,注入對象,也是通過這個構造流程來構建bean並注入
	if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME ||
			mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
		MutablePropertyValues newPvs = new MutablePropertyValues(pvs);

		// Add property values based on autowire by name if applicable.
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_NAME) {
			autowireByName(beanName, mbd, bw, newPvs);
		}

		// Add property values based on autowire by type if applicable.
		if (mbd.getResolvedAutowireMode() == RootBeanDefinition.AUTOWIRE_BY_TYPE) {
			autowireByType(beanName, mbd, bw, newPvs);
		}

		pvs = newPvs;
	}

	boolean hasInstAwareBpps = hasInstantiationAwareBeanPostProcessors();
	boolean needsDepCheck = (mbd.getDependencyCheck() != RootBeanDefinition.DEPENDENCY_CHECK_NONE);

	// 調用InstantiationAwareBeanPostProcessor#postProcessPropertyValues方法
	if (hasInstAwareBpps || needsDepCheck) {
		PropertyDescriptor[] filteredPds = filterPropertyDescriptorsForDependencyCheck(bw, mbd.allowCaching);
		if (hasInstAwareBpps) {
			for (BeanPostProcessor bp : getBeanPostProcessors()) {
				if (bp instanceof InstantiationAwareBeanPostProcessor) {
					InstantiationAwareBeanPostProcessor ibp = (InstantiationAwareBeanPostProcessor) bp;
					pvs = ibp.postProcessPropertyValues(pvs, filteredPds, bw.getWrappedInstance(), beanName);
					if (pvs == null) {
						return;
					}
				}
			}
		}
		if (needsDepCheck) {
			checkDependencies(beanName, mbd, filteredPds, pvs);
		}
	}

	applyPropertyValues(beanName, mbd, bw, pvs);
}

初始化bean

AbstractAutowireCapableBeanFactory#initializeBean

protected Object initializeBean(final String beanName, final Object bean, RootBeanDefinition mbd) {
	if (System.getSecurityManager() != null) {
		AccessController.doPrivileged(new PrivilegedAction<Object>() {
			@Override
			public Object run() {
				invokeAwareMethods(beanName, bean);
				return null;
			}
		}, getAccessControlContext());
	}
	else {
		invokeAwareMethods(beanName, bean);
	}

	// 調用BeanPostProcessor#postProcessBeforeInitialization方法
	Object wrappedBean = bean;
	if (mbd == null || !mbd.isSynthetic()) {
		wrappedBean = applyBeanPostProcessorsBeforeInitialization(wrappedBean, beanName);
	}

	try {
		// 如果bean實現了InitializingBean接口則執行afterPropertiesSet方法,或者如果指定了init mehod,執行該init method
		invokeInitMethods(beanName, wrappedBean, mbd);
	}
	catch (Throwable ex) {
		throw new BeanCreationException(
				(mbd != null ? mbd.getResourceDescription() : null),
				beanName, "Invocation of init method failed", ex);
	}

	// 執行BeanPostProcessor#postProcessAfterInitialization方法
	// 一般做代理類的,通常會在這一部進行代理類的替換
	if (mbd == null || !mbd.isSynthetic()) {
		wrappedBean = applyBeanPostProcessorsAfterInitialization(wrappedBean, beanName);
	}
	return wrappedBean;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章