天天看點

Spring容器啟動流程

作者:做好一個程式猿

一、前言知識

  1. Spring會将所有交由Spring管理的類,掃描其class檔案,将其解析成BeanDefinition,在BeanDefinition中會描述類的資訊,例如:這個類是否是單例的,Bean的類型,是否是懶加載,依賴哪些類,自動裝配的模型。Spring建立對象時,就是根據BeanDefinition中的資訊來建立Bean。
  2. Spring容器在本文可以簡單了解為DefaultListableBeanFactory,它是BeanFactory的實作類,這個類有幾個非常重要的屬性:
    1. beanDefinitionMap是一個map,用來存放bean所對應的BeanDefinition;
    2. beanDefinitionNames是一個List集合,用來存放所有bean的name;
    3. singletonObjects是一個Map,用來存放所有建立好的單例Bean。
  1. Spring中有很多後置處理器,但最終可以分為兩種,一種是BeanFactoryPostProcessor,一種是BeanPostProcessor。前者的用途是用來幹預BeanFactory的建立過程,後者是用來幹預Bean的建立過程。後置處理器的作用十分重要,bean的建立以及AOP的實作全部依賴後置處理器。

二、源碼解析

2.1 基于注解

流程概述

本文是基于 java-config 技術分析源碼,是以這裡的入口是 AnnotationConfigApplicationContext ,如果是使用 xml 分析,那麼入口即為 ClassPathXmlApplicationContext ,它們倆的共同特征便是都繼承了 AbstractApplicationContext 類,而大名鼎鼎的 refresh()便是在這個類中定義的。我們接着分析 AnnotationConfigApplicationContext 類,入口如下:

AnnotationConfigApplicationContext applicationContext =
                new AnnotationConfigApplicationContext(Config.class);

// 初始化容器
public AnnotationConfigApplicationContext(Class<?>... annotatedClasses) {
    this();
    // 注冊配置類 BeanDefinition 到容器
    register(annotatedClasses);
    // 加載或者重新整理容器中的Bean
    refresh();
}
           

整個Spring容器的啟動流程可以繪制成如下流程圖:

Spring容器啟動流程

spring容器的初始化時,通過this()調用了無參構造函數,主要做了以下三個事情:

(1)執行個體化BeanFactory【DefaultListableBeanFactory】工廠,用于生成Bean對象。

(2)執行個體化BeanDefinitionReader注解配置讀取器,用于對特定注解(如@Service、@Repository)的類進行讀取轉化成 BeanDefinition 對象,(BeanDefinition 是 Spring 中極其重要的一個概念,它存儲了 bean 對象的所有特征資訊,如是否單例,是否懶加載,factoryBeanName 等)

(3)執行個體化ClassPathBeanDefinitionScanner路徑掃描器,用于對指定的包目錄進行掃描查找 bean 對象。

完整流程

  1. this()調用
    1. this()會調用AnnotationConfigApplicationContext無參構造方法,而在Java的繼承中,會先調用父類的構造方法。是以會先調用AnnotationConfigApplicationContext的父類GeniricApplicationContext的構造方法,在父類中初始化beanFactory,即直接new了一個DefaultListableBeanFactory。
public GenericApplicationContext() {    
    this.beanFactory = new DefaultListableBeanFactory();
}           
    1. 在this()中通過new AnnotatedBeanDefinitionReader(this)執行個體化了一個Bean讀取器,并向容器中添加後置處理器。
      1. 向容器中添加了2個beanFactory後置處理器:ConfigurationClassPostProcessor 和EventListenerMethodProcessor。
      2. 向容器中添加了兩個bean後置處理器:AutowiredAnnotationBeanPostProcessor 和CommonAnnotationBeanPostProcessor。
      3. 向容器中添加普通元件:DefaultEventListenerFactory。
public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry) {
		this(registry, getOrCreateEnvironment(registry));
	}

public AnnotatedBeanDefinitionReader(BeanDefinitionRegistry registry, Environment environment) {
		Assert.notNull(registry, "BeanDefinitionRegistry must not be null");
		Assert.notNull(environment, "Environment must not be null");
		this.registry = registry;
		this.conditionEvaluator = new ConditionEvaluator(registry, environment, null);
		AnnotationConfigUtils.registerAnnotationConfigProcessors(this.registry);
	}

public static void registerAnnotationConfigProcessors(BeanDefinitionRegistry registry) {
		registerAnnotationConfigProcessors(registry, null);
	}


public static Set<BeanDefinitionHolder> registerAnnotationConfigProcessors(
			BeanDefinitionRegistry registry, @Nullable Object source) {

		DefaultListableBeanFactory beanFactory = unwrapDefaultListableBeanFactory(registry);
		if (beanFactory != null) {
			if (!(beanFactory.getDependencyComparator() instanceof AnnotationAwareOrderComparator)) {
				beanFactory.setDependencyComparator(AnnotationAwareOrderComparator.INSTANCE);
			}
			if (!(beanFactory.getAutowireCandidateResolver() instanceof ContextAnnotationAutowireCandidateResolver)) {
				beanFactory.setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());
			}
		}

		Set<BeanDefinitionHolder> beanDefs = new LinkedHashSet<>(8);

		if (!registry.containsBeanDefinition(CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(ConfigurationClassPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, CONFIGURATION_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(AutowiredAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, AUTOWIRED_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JSR-250 support, and if present add the CommonAnnotationBeanPostProcessor.
		if (jsr250Present && !registry.containsBeanDefinition(COMMON_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(CommonAnnotationBeanPostProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, COMMON_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		// Check for JPA support, and if present add the PersistenceAnnotationBeanPostProcessor.
		if (jpaPresent && !registry.containsBeanDefinition(PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition();
			try {
				def.setBeanClass(ClassUtils.forName(PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME,
						AnnotationConfigUtils.class.getClassLoader()));
			}
			catch (ClassNotFoundException ex) {
				throw new IllegalStateException(
						"Cannot load optional framework class: " + PERSISTENCE_ANNOTATION_PROCESSOR_CLASS_NAME, ex);
			}
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, PERSISTENCE_ANNOTATION_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_PROCESSOR_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(EventListenerMethodProcessor.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_PROCESSOR_BEAN_NAME));
		}

		if (!registry.containsBeanDefinition(EVENT_LISTENER_FACTORY_BEAN_NAME)) {
			RootBeanDefinition def = new RootBeanDefinition(DefaultEventListenerFactory.class);
			def.setSource(source);
			beanDefs.add(registerPostProcessor(registry, def, EVENT_LISTENER_FACTORY_BEAN_NAME));
		}

		return beanDefs;
	}           
    1. 通過new ClassPathBeanDefinitionScanner(this)執行個體化了一個可以對使用者指定的包目錄進行掃描查找 bean 對象的一個路徑掃描器。
  1. register(annotatedClasses)将傳入的配置類annotatedClasses解析成BeanDefinition(實際類型為AnnotatedGenericBeanDefinition),然後放入到BeanDefinitionMap中,這樣後面在ConfigurationClassPostProcessor中能解析annotatedClasses,此時隻是注冊BeanDefinition資訊,沒有執行個體化。
<T> void doRegisterBean(Class<T> annotatedClass, @Nullable Supplier<T> instanceSupplier, @Nullable String name,
		@Nullable Class<? extends Annotation>[] qualifiers, BeanDefinitionCustomizer... definitionCustomizers) {
	// 解析傳入的配置類,實際上這個方法既可以解析配置類,也可以解析 Spring bean 對象
	AnnotatedGenericBeanDefinition abd = new AnnotatedGenericBeanDefinition(annotatedClass);
	// 判斷是否需要跳過,判斷依據是此類上有沒有 @Conditional 注解
	if (this.conditionEvaluator.shouldSkip(abd.getMetadata())) {
		return;
	}

	abd.setInstanceSupplier(instanceSupplier);
	ScopeMetadata scopeMetadata = this.scopeMetadataResolver.resolveScopeMetadata(abd);
	abd.setScope(scopeMetadata.getScopeName());
	String beanName = (name != null ? name : this.beanNameGenerator.generateBeanName(abd, this.registry));
	// 處理類上的通用注解
	AnnotationConfigUtils.processCommonDefinitionAnnotations(abd);
	if (qualifiers != null) {
		for (Class<? extends Annotation> qualifier : qualifiers) {
			if (Primary.class == qualifier) {
				abd.setPrimary(true);
			}
			else if (Lazy.class == qualifier) {
				abd.setLazyInit(true);
			}
			else {
				abd.addQualifier(new AutowireCandidateQualifier(qualifier));
			}
		}
	}
	// 封裝成一個 BeanDefinitionHolder
	for (BeanDefinitionCustomizer customizer : definitionCustomizers) {
		customizer.customize(abd);
	}
	BeanDefinitionHolder definitionHolder = new BeanDefinitionHolder(abd, beanName);
	// 處理 scopedProxyMode
	definitionHolder = AnnotationConfigUtils.applyScopedProxyMode(scopeMetadata, definitionHolder, this.registry);

	// 把 BeanDefinitionHolder 注冊到 registry
	BeanDefinitionReaderUtils.registerBeanDefinition(definitionHolder, this.registry);
}
           
  1. 執行refresh()方法refresh()方法是整個Spring容器的核心,在這個方法中進行了bean的執行個體化、初始化、自動裝配、AOP等功能。

重點方法: AbstractApplicationContext.refresh( )

Spring容器啟動流程

上文中我們知道了如何去初始化一個 IOC 容器,那麼接下來就是讓這個 IOC 容器真正起作用的時候了:即先掃描出要放入容器的 bean,将其包裝成 BeanDefinition 對象,然後通過反射建立 bean,并完成指派操作,這個就是 IOC 容器最簡單的功能了。但是看上圖,明顯 Spring 的初始化過程比這個多的多,下面我們就詳細分析一下這樣設計的意義:

如果使用者想在掃描完 bean 之後做一些自定義的操作:假設容器中包含了 a 和 b,那麼就動态向容器中注入 c,不滿足就注入 d,這種操作 Spring 也是支援的,可以使用它提供的 BeanFactoryPostProcessor 後置處理器,對應的是上圖中的 invokeBeanFactoryPostProcessors 操作。

如果使用者還想在 bean 的初始化前後做一些操作呢?比如生成代理對象,修改對象屬性等,Spring 為我們提供了 BeanPostProcessor 後置處理器,實際上 Spring 容器中的大多數功能都是通過 Bean 後置處理器完成的,Spring 也是給我們提供了添加入口,對應的是上圖中的 registerBeanPostProcessors 操作。

容器建立過程中,如果使用者想監聽容器啟動、重新整理等事件,根據這些事件做一些自定義的操作?Spring 也早已為我們考慮到了,提供了添加監聽器接口和容器事件通知接口,對應的是上圖中的 registerListeners 操作。

public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		// 1. 重新整理前的預處理
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		// 2. 擷取 beanFactory,即前面建立的【DefaultListableBeanFactory】
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		// 3. 預處理 beanFactory,向容器中添加一些元件
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			// 4. 子類通過重寫這個方法可以在 BeanFactory 建立并與準備完成以後做進一步的設定
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			// 5. 執行 BeanFactoryPostProcessor 方法,beanFactory 後置處理器
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			// 6. 注冊 BeanPostProcessors,bean 後置處理器
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			// 7. 初始化 MessageSource 元件(做國際化功能;消息綁定,消息解析)
			initMessageSource();

			// Initialize event multicaster for this context.
			// 8. 初始化事件派發器,在注冊監聽器時會用到
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			// 9. 留給子容器(子類),子類重寫這個方法,在容器重新整理的時候可以自定義邏輯,web 場景下會使用
			onRefresh();

			// Check for listener beans and register them.
			// 10. 注冊監聽器,派發之前步驟産生的一些事件(可能沒有)
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			// 11. 初始化所有的非單執行個體 bean
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			// 12. 釋出容器重新整理完成事件
			finishRefresh();
		}

		...
		
	}
}           

refresh()主要用于容器的重新整理,Spring 中的每一個容器都會調用 refresh() 方法進行重新整理,無論是 Spring 的父子容器,還是 Spring Cloud Feign 中的 feign 隔離容器,每一個容器都會調用這個方法完成初始化。refresh()可劃分為上述的12個步驟,其中比較重要的步驟下面會有詳細說明。

先總結一下refresh()方法每一步主要的功能:

  1. prepareRefresh()重新整理前的預處理:
    1. initPropertySources():初始化一些屬性設定,子類自定義個性化的屬性設定方法;
    2. getEnvironment().validateRequiredProperties():檢驗屬性的合法性
    3. earlyApplicationEvents = new LinkedHashSet<ApplicationEvent>():儲存容器中的一些早期的事件;
  1. obtainFreshBeanFactory():擷取在容器初始化時建立的BeanFactory:
    1. refreshBeanFactory():重新整理BeanFactory,設定序列化ID;
    2. getBeanFactory():傳回初始化中的GenericApplicationContext建立的BeanFactory對象,即【DefaultListableBeanFactory】類型
  1. prepareBeanFactory(beanFactory):BeanFactory的預處理工作,向容器中添加一些元件:
    1. 設定BeanFactory的類加載器、設定表達式解析器等等
    2. 添加BeanPostProcessor【ApplicationContextAwareProcessor】
    3. 設定忽略自動裝配的接口:EnvironmentAware、EmbeddedValueResolverAware、ResourceLoaderAware、ApplicationEventPublisherAware、MessageSourceAware、ApplicationContextAware;
    4. 注冊可以解析的自動裝配類,即可以在任意元件中通過注解自動注入:BeanFactory、ResourceLoader、ApplicationEventPublisher、ApplicationContext
    5. 添加BeanPostProcessor【ApplicationListenerDetector】
    6. 添加編譯時的AspectJ;
    7. 給BeanFactory中注冊的3個元件:environment【ConfigurableEnvironment】、systemProperties【Map<String, Object>】、systemEnvironment【Map<String, Object>】
  1. postProcessBeanFactory(beanFactory):子類重寫該方法,可以實作在BeanFactory建立并預處理完成以後做進一步的設定。
  2. invokeBeanFactoryPostProcessors(beanFactory):在BeanFactory标準初始化之後執行BeanFactoryPostProcessor的方法,即BeanFactory的後置處理器:
    1. 先執行BeanDefinitionRegistryPostProcessor: postProcessor.postProcessBeanDefinitionRegistry(registry)
      1. 擷取所有的實作了BeanDefinitionRegistryPostProcessor接口類型的集合
      2. 先執行實作了PriorityOrdered優先級接口的BeanDefinitionRegistryPostProcessor
      3. 再執行實作了Ordered順序接口的BeanDefinitionRegistryPostProcessor
      4. 最後執行沒有實作任何優先級或者是順序接口的BeanDefinitionRegistryPostProcessors
    1. 再執行BeanFactoryPostProcessor的方法:postProcessor.postProcessBeanFactory(beanFactory)
      1. 擷取所有的實作了BeanFactoryPostProcessor接口類型的集合
      2. 先執行實作了PriorityOrdered優先級接口的BeanFactoryPostProcessor
      3. 再執行實作了Ordered順序接口的BeanFactoryPostProcessor
      4. 最後執行沒有實作任何優先級或者是順序接口的BeanFactoryPostProcessor
  1. registerBeanPostProcessors(beanFactory):向容器中注冊Bean的後置處理器BeanPostProcessor,它的主要作用是幹預Spring初始化bean的流程,進而完成代理、自動注入、循環依賴等功能
    1. 擷取所有實作了BeanPostProcessor接口類型的集合:
    2. 先注冊實作了PriorityOrdered優先級接口的BeanPostProcessor;
    3. 再注冊實作了Ordered優先級接口的BeanPostProcessor;
    4. 最後注冊沒有實作任何優先級接口的BeanPostProcessor;
    5. 最終注冊MergedBeanDefinitionPostProcessor類型的BeanPostProcessor:beanFactory.addBeanPostProcessor(postProcessor);
    6. 給容器注冊一個ApplicationListenerDetector:用于在Bean建立完成後檢查是否是ApplicationListener,如果是,就把Bean放到容器中儲存起來:applicationContext.addApplicationListener((ApplicationListener<?>) bean);此時容器中預設有6個預設的BeanProcessor(無任何代理模式下)
  1. initMessageSource():初始化MessageSource元件,主要用于做國際化功能,消息綁定與消息解析:
  2. initApplicationEventMulticaster():初始化事件派發器,在注冊監聽器時會用到
    1. 看BeanFactory容器中是否存在自定義的ApplicationEventMulticaster:如果有,直接從容器中擷取;如果沒有,則建立一個SimpleApplicationEventMulticaster
    2. 将建立的ApplicationEventMulticaster添加到BeanFactory中,以後其他元件就可以直接自動注入。
  1. onRefresh():留給子容器、子類重寫這個方法,在容器重新整理的時候可以自定義邏輯。
  2. registerListeners():注冊監聽器:将容器中所有的ApplicationListener注冊到事件派發器中,并派發之前步驟産生的事件:
  3. finishBeanFactoryInitialization(beanFactory):初始化所有剩下的單執行個體bean,核心方法是preInstantiateSingletons(),會調用getBean()方法建立對象;
    1. 擷取容器中的所有beanDefinitionName,依次進行初始化和建立對象
    2. 擷取Bean的定義資訊RootBeanDefinition,它表示自己的BeanDefinition和可能存在父類的BeanDefinition合并後的對象
    3. 如果Bean滿足這三個條件:非抽象的,單執行個體,非懶加載,則執行單例Bean建立流程:
    4. 所有Bean都利用getBean()建立完成以後,檢查所有的Bean是否為SmartInitializingSingleton接口的,如果是;就執行afterSingletonsInstantiated();
  1. finishRefresh():釋出BeanFactory容器重新整理完成事件:
    1. nitLifecycleProcessor():初始化和生命周期有關的後置處理器:預設從容器中找是否有lifecycleProcessor的元件【LifecycleProcessor】,如果沒有,則建立一個DefaultLifecycleProcessor()加入到容器;
    2. getLifecycleProcessor().onRefresh():拿到前面定義的生命周期處理器(LifecycleProcessor)回調onRefresh()方法
    3. publishEvent(new ContextRefreshedEvent(this)):釋出容器重新整理完成事件;
    4. liveBeansView.registerApplicationContext(this);

下面我們一起看一下上面标紅的重點方法的源碼

BeanFactory的預處理

org.springframework.context.support.AbstractApplicationContext#prepareBeanFactory

顧名思義,這個接口是為 beanFactory 工廠添加一些内置元件,預處理過程。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	// 設定 classLoader
	beanFactory.setBeanClassLoader(getClassLoader());
	//設定 bean 表達式解析器
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	// 添加一個 BeanPostProcessor【ApplicationContextAwareProcessor】
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));

	// 設定忽略自動裝配的接口,即不能通過注解自動注入
	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.
	// 注冊可以解析的自動裝配類,即可以在任意元件中通過注解自動注入
	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.
	// 添加一個 BeanPostProcessor【ApplicationListenerDetector】
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this));

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	// 添加編譯時的 AspectJ
	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()));
	}

	// Register default environment beans.
	// 注冊 environment 元件,類型是【ConfigurableEnvironment】
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	// 注冊 systemProperties 元件,類型是【Map<String, Object>】
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	// 注冊 systemEnvironment 元件,類型是【Map<String, Object>】
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}           

執行BeanFactory的後置處理器

org.springframework.context.support.PostProcessorRegistrationDelegate#invokeBeanFactoryPostProcessors

Spring 在掃描完所有的 bean 轉成 BeanDefinition 時候,我們是可以做一些自定義操作的,這得益于 Spring 為我們提供的 BeanFactoryPostProcessor 接口。

其中 BeanFactoryPostProcessor 又有一個子接口 BeanDefinitionRegistryPostProcessor ,前者會把 ConfigurableListableBeanFactory 暴露給我們使用,後者會把 BeanDefinitionRegistry 注冊器暴露給我們使用,一旦擷取到注冊器,我們就可以按需注入了,例如搞定這種需求:假設容器中包含了 a 和 b,那麼就動态向容器中注入 c,不滿足就注入 d。

同時 Spring 是允許我們控制同類型元件的順序,比如在 AOP 中我們常用的 @Order 注解,這裡的 BeanFactoryPostProcessor 接口當然也是提供了順序,最先被執行的是實作了 PriorityOrdered 接口的實作類,然後再到實作了 Ordered 接口的實作類,最後就是剩下來的正常 BeanFactoryPostProcessor 類。

Spring容器啟動流程

此時再看上圖,是不是發現比較簡單了,首先會回調 postProcessBeanDefinitionRegistry() 方法,然後再回調 postProcessBeanFactory() 方法,最後注意順序即可,下面一起看看具體的代碼實作吧。

public static void invokeBeanFactoryPostProcessors(
		ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
	// beanFactoryPostProcessors 這個參數是指使用者通過 AnnotationConfigApplicationContext.addBeanFactoryPostProcessor() 方法手動傳入的 BeanFactoryPostProcessor,沒有交給 spring 管理
	// Invoke BeanDefinitionRegistryPostProcessors first, if any.
	// 代表執行過的 BeanDefinitionRegistryPostProcessor
	Set<String> processedBeans = new HashSet<>();
 
	if (beanFactory instanceof BeanDefinitionRegistry) {
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
		// 正常後置處理器集合,即實作了 BeanFactoryPostProcessor 接口
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
		// 注冊後置處理器集合,即實作了 BeanDefinitionRegistryPostProcessor 接口
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
		// 處理自定義的 beanFactoryPostProcessors(指調用 context.addBeanFactoryPostProcessor() 方法),一般這裡都沒有
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
				BeanDefinitionRegistryPostProcessor registryProcessor =
						(BeanDefinitionRegistryPostProcessor) postProcessor;
				// 調用 postProcessBeanDefinitionRegistry 方法
				registryProcessor.postProcessBeanDefinitionRegistry(registry);
				registryProcessors.add(registryProcessor);
			}
			else {
				regularPostProcessors.add(postProcessor);
			}
		}
 
		// Do not initialize FactoryBeans here: We need to leave all regular beans
		// uninitialized to let the bean factory post-processors apply to them!
		// Separate between BeanDefinitionRegistryPostProcessors that implement
		// PriorityOrdered, Ordered, and the rest.
		// 定義一個變量 currentRegistryProcessors,表示目前要處理的 BeanFactoryPostProcessors
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
 
		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
		// 首先,從容器中查找實作了 PriorityOrdered 接口的 BeanDefinitionRegistryPostProcessor 類型,這裡隻會查找出一個【ConfigurationClassPostProcessor】
		String[] postProcessorNames =
				beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			// 判斷是否實作了 PriorityOrdered 接口
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				// 添加到 currentRegistryProcessors
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				// 添加到 processedBeans,表示已經處理過這個類了
				processedBeans.add(ppName);
			}
		}
		// 設定排列順序
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		// 添加到 registry 中
		registryProcessors.addAll(currentRegistryProcessors);
		// 執行 [postProcessBeanDefinitionRegistry] 回調方法
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		// 将 currentRegistryProcessors 變量清空,下面會繼續用到
		currentRegistryProcessors.clear();
 
		// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
		// 接下來,從容器中查找實作了 Ordered 接口的 BeanDefinitionRegistryPostProcessors 類型,這裡可能會查找出多個
		// 因為【ConfigurationClassPostProcessor】已經完成了 postProcessBeanDefinitionRegistry() 方法,已經向容器中完成掃描工作,是以容器會有很多個元件
		postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			// 判斷 processedBeans 是否處理過這個類,且是否實作 Ordered 接口
			if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		// 設定排列順序
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		// 添加到 registry 中
		registryProcessors.addAll(currentRegistryProcessors);
		// 執行 [postProcessBeanDefinitionRegistry] 回調方法
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		// 将 currentRegistryProcessors 變量清空,下面會繼續用到
		currentRegistryProcessors.clear();
 
		// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
		// 最後,從容器中查找剩餘所有正常的 BeanDefinitionRegistryPostProcessors 類型
		boolean reiterate = true;
		while (reiterate) {
			reiterate = false;
			// 根據類型從容器中查找
			postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
			for (String ppName : postProcessorNames) {
				// 判斷 processedBeans 是否處理過這個類
				if (!processedBeans.contains(ppName)) {
					// 添加到 currentRegistryProcessors
					currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
					// 添加到 processedBeans,表示已經處理過這個類了
					processedBeans.add(ppName);
					// 将辨別設定為 true,繼續循環查找,可能随時因為防止下面調用了 invokeBeanDefinitionRegistryPostProcessors() 方法引入新的後置處理器
					reiterate = true;
				}
			}
			// 設定排列順序
			sortPostProcessors(currentRegistryProcessors, beanFactory);
			// 添加到 registry 中
			registryProcessors.addAll(currentRegistryProcessors);
			// 執行 [postProcessBeanDefinitionRegistry] 回調方法
			invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
			// 将 currentRegistryProcessors 變量清空,因為下一次循環可能會用到
			currentRegistryProcessors.clear();
		}
 
		// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
		// 現在執行 registryProcessors 的 [postProcessBeanFactory] 回調方法
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		// 執行 regularPostProcessors 的 [postProcessBeanFactory] 回調方法,也包含使用者手動調用 addBeanFactoryPostProcessor() 方法添加的 BeanFactoryPostProcessor
		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!
	// 從容器中查找實作了 BeanFactoryPostProcessor 接口的類
	String[] postProcessorNames =
			beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
 
	// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	// 表示實作了 PriorityOrdered 接口的 BeanFactoryPostProcessor
	List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	// 表示實作了 Ordered 接口的 BeanFactoryPostProcessor
	List<String> orderedPostProcessorNames = new ArrayList<>();
	// 表示剩下來的正常的 BeanFactoryPostProcessors
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	for (String ppName : postProcessorNames) {
		// 判斷是否已經處理過,因為 postProcessorNames 其實包含了上面步驟處理過的 BeanDefinitionRegistry 類型
		if (processedBeans.contains(ppName)) {
			// skip - already processed in first phase above
		}
		// 判斷是否實作了 PriorityOrdered 接口
		else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
		}
		// 判斷是否實作了 Ordered 接口
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		// 剩下所有正常的
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}
 
	// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
	// 先将 priorityOrderedPostProcessors 集合排序
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	// 執行 priorityOrderedPostProcessors 的 [postProcessBeanFactory] 回調方法
	invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
 
	// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
	// 接下來,把 orderedPostProcessorNames 轉成 orderedPostProcessors 集合
	List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : orderedPostProcessorNames) {
		orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	// 将 orderedPostProcessors 集合排序
	sortPostProcessors(orderedPostProcessors, beanFactory);
	// 執行 orderedPostProcessors 的 [postProcessBeanFactory] 回調方法
	invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
 
	// Finally, invoke all other BeanFactoryPostProcessors.
	// 最後把 nonOrderedPostProcessorNames 轉成 nonOrderedPostProcessors 集合,這裡隻有一個,myBeanFactoryPostProcessor
	List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String postProcessorName : nonOrderedPostProcessorNames) {
		nonOrderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
	}
	// 執行 nonOrderedPostProcessors 的 [postProcessBeanFactory] 回調方法
	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();
}           

流程小結

(1)先執行BeanDefinitionRegistryPostProcessor: postProcessor.postProcessBeanDefinitionRegistry(registry)
    ① 擷取所有的實作了BeanDefinitionRegistryPostProcessor接口類型的集合
    ② 先執行實作了PriorityOrdered優先級接口的BeanDefinitionRegistryPostProcessor
    ③ 再執行實作了Ordered順序接口的BeanDefinitionRegistryPostProcessor
    ④ 最後執行沒有實作任何優先級或者是順序接口的BeanDefinitionRegistryPostProcessors        
(2)再執行BeanFactoryPostProcessor的方法:postProcessor.postProcessBeanFactory(beanFactory)
    ① 擷取所有的實作了BeanFactoryPostProcessor接口類型的集合
    ② 先執行實作了PriorityOrdered優先級接口的BeanFactoryPostProcessor
    ③ 再執行實作了Ordered順序接口的BeanFactoryPostProcessor
    ④ 最後執行沒有實作任何優先級或者是順序接口的BeanFactoryPostProcessor           

注冊Bean的後置處理器

org.springframework.context.support.PostProcessorRegistrationDelegate#registerBeanPostProcessors

這一步是向容器中注入 BeanPostProcessor 後置處理器,注意這裡僅僅是向容器中注入而非使用。關于 BeanPostProcessor ,它的作用主要是會幹預 Spring 初始化 bean 的流程,進而完成代理、自動注入、循環依賴等各種功能。

public static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
 
	// 從容器中擷取 BeanPostProcessor 類型
	String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
 
	// Register BeanPostProcessorChecker that logs an info message when
	// a bean is created during BeanPostProcessor instantiation, i.e. when
	// a bean is not eligible for getting processed by all BeanPostProcessors.
	int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
	// 向容器中添加【BeanPostProcessorChecker】,主要是用來檢查是不是有 bean 已經初始化完成了,
	// 如果沒有執行所有的 beanPostProcessor(用數量來判斷),如果有就會列印一行 info 日志
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
 
	// Separate between BeanPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	// 存放實作了 PriorityOrdered 接口的 BeanPostProcessor
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
	// 存放 MergedBeanDefinitionPostProcessor 類型的 BeanPostProcessor
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
	// 存放實作了 Ordered 接口的 BeanPostProcessor 的 name
	List<String> orderedPostProcessorNames = new ArrayList<>();
	// 存放剩下來普通的 BeanPostProcessor 的 name
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();
	// 從 beanFactory 中查找 postProcessorNames 裡的 bean,然後放到對應的集合中
	for (String ppName : postProcessorNames) {
		// 判斷有無實作 PriorityOrdered 接口
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			priorityOrderedPostProcessors.add(pp);
			// 如果實作了 PriorityOrdered 接口,且屬于 MergedBeanDefinitionPostProcessor
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				// 把 MergedBeanDefinitionPostProcessor 類型的添加到 internalPostProcessors 集合中
				internalPostProcessors.add(pp);
			}
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}
 
	// First, register the BeanPostProcessors that implement PriorityOrdered.
	// 給 priorityOrderedPostProcessors 排序
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	// 先注冊實作了 PriorityOrdered 接口的 beanPostProcessor
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
 
	// Next, register the BeanPostProcessors that implement Ordered.
	// 從 beanFactory 中查找 orderedPostProcessorNames 裡的 bean,然後放到對應的集合中
	List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>();
	for (String ppName : orderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		orderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	// 給 orderedPostProcessors 排序
	sortPostProcessors(orderedPostProcessors, beanFactory);
	// 再注冊實作了 Ordered 接口的 beanPostProcessor
	registerBeanPostProcessors(beanFactory, orderedPostProcessors);
 
	// Now, register all regular BeanPostProcessors.
	List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>();
	for (String ppName : nonOrderedPostProcessorNames) {
		BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
		nonOrderedPostProcessors.add(pp);
		if (pp instanceof MergedBeanDefinitionPostProcessor) {
			internalPostProcessors.add(pp);
		}
	}
	// 再注冊正常的 beanPostProcessor
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);
 
	// Finally, re-register all internal BeanPostProcessors.
	// 排序 MergedBeanDefinitionPostProcessor 這種類型的 beanPostProcessor
	sortPostProcessors(internalPostProcessors, beanFactory);
	// 最後注冊 MergedBeanDefinitionPostProcessor 類型的 beanPostProcessor
	registerBeanPostProcessors(beanFactory, internalPostProcessors);
 
	// Re-register post-processor for detecting inner beans as ApplicationListeners,
	// moving it to the end of the processor chain (for picking up proxies etc).
	// 給容器中添加【ApplicationListenerDetector】 beanPostProcessor,判斷是不是監聽器,如果是就把 bean 放到容器中儲存起來
	// 此時容器中預設會有 6 個内置的 beanPostProcessor
		// 0 = {ApplicationContextAwareProcessor@1632}
		//	1 = {ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor@1633}
		//	2 = {PostProcessorRegistrationDelegate$BeanPostProcessorChecker@1634}
		//	3 = {CommonAnnotationBeanPostProcessor@1635}
		//	4 = {AutowiredAnnotationBeanPostProcessor@1636}
		//	5 = {ApplicationListenerDetector@1637}
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}           

初始化事件派發器

org.springframework.context.support.AbstractApplicationContext#initApplicationEventMulticaster:

在整個容器建立過程中,Spring 會釋出很多容器事件,如容器啟動、重新整理、關閉等,這個功能的實作得益于這裡的 ApplicationEventMulticaster 廣播器元件,通過它來派發事件通知。

protected void initApplicationEventMulticaster() {
	// 擷取 beanFactory
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	// 看看容器中是否有自定義的 applicationEventMulticaster
	if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
		// 有就從容器中擷取指派
		this.applicationEventMulticaster =
				beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
		if (logger.isTraceEnabled()) {
			logger.trace("Using ApplicationEventMulticaster [" + this.applicationEventMulticaster + "]");
		}
	}
	else {
		// 沒有,就建立一個 SimpleApplicationEventMulticaster
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
		// 将建立的 ApplicationEventMulticaster 添加到 BeanFactory 中, 其他元件就可以自動注入了
		beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
		if (logger.isTraceEnabled()) {
			logger.trace("No '" + APPLICATION_EVENT_MULTICASTER_BEAN_NAME + "' bean, using " +
					"[" + this.applicationEventMulticaster.getClass().getSimpleName() + "]");
		}
	}
}           

注冊ApplicationListener監聽器

org.springframework.context.support.AbstractApplicationContext#registerListeners:

這一步主要是将容器中所有的ApplicationListener注冊到事件派發器中,并派發之前步驟産生的事件。

protected void registerListeners() {
	// Register statically specified listeners first.
	// 擷取之前步驟中儲存的 ApplicationListener
	for (ApplicationListener<?> listener : getApplicationListeners()) {
		// getApplicationEventMulticaster() 就是擷取之前步驟初始化的 applicationEventMulticaster
		getApplicationEventMulticaster().addApplicationListener(listener);
	}
 
	// Do not initialize FactoryBeans here: We need to leave all regular beans
	// uninitialized to let post-processors apply to them!
	// 從容器中擷取所有的 ApplicationListener
	String[] listenerBeanNames = getBeanNamesForType(ApplicationListener.class, true, false);
	for (String listenerBeanName : listenerBeanNames) {
		getApplicationEventMulticaster().addApplicationListenerBean(listenerBeanName);
	}
 
	// Publish early application events now that we finally have a multicaster...
	// 派發之前步驟産生的 application events
	Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
	this.earlyApplicationEvents = null;
	if (earlyEventsToProcess != null) {
		for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
			getApplicationEventMulticaster().multicastEvent(earlyEvent);
		}
	}
}           

初始化所有的單例Bean

org.springframework.beans.factory.support.DefaultListableBeanFactory#preInstantiateSingletons:

在前面的步驟中,Spring 的大多數元件都已經初始化完畢了,剩下來的這個步驟就是初始化所有剩餘的單執行個體 bean,Spring主要是通過preInstantiateSingletons()方法把容器中的 bean 都初始化完畢。這裡我們就不細講Bean的建立流程了。

public void preInstantiateSingletons() throws BeansException {
	if (logger.isTraceEnabled()) {
		logger.trace("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.
	// 擷取容器中的所有 beanDefinitionName
	List<String> beanNames = new ArrayList<>(this.beanDefinitionNames);
 
	// Trigger initialization of all non-lazy singleton beans...
	// 循環進行初始化和建立對象
	for (String beanName : beanNames) {
		// 擷取 RootBeanDefinition,它表示自己的 BeanDefinition 和可能存在父類的 BeanDefinition 合并後的對象
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		// 如果是非抽象的,且單執行個體,非懶加載
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			// 如果是 factoryBean,利用下面這種方法建立對象
			if (isFactoryBean(beanName)) {
				// 如果是 factoryBean,則 加上 &,先建立工廠 bean
				Object bean = getBean(FACTORY_BEAN_PREFIX + beanName);
				if (bean instanceof FactoryBean) {
					final FactoryBean<?> factory = (FactoryBean<?>) bean;
					boolean isEagerInit;
					if (System.getSecurityManager() != null && factory instanceof SmartFactoryBean) {
						isEagerInit = AccessController.doPrivileged((PrivilegedAction<Boolean>)
										((SmartFactoryBean<?>) factory)::isEagerInit,
								getAccessControlContext());
					}
					else {
						isEagerInit = (factory instanceof SmartFactoryBean &&
								((SmartFactoryBean<?>) factory).isEagerInit());
					}
					if (isEagerInit) {
						getBean(beanName);
					}
				}
			}
			else {
				// 不是工廠 bean,用這種方法建立對象
				getBean(beanName);
			}
		}
	}
 
	// Trigger post-initialization callback for all applicable beans...
	for (String beanName : beanNames) {
		Object singletonInstance = getSingleton(beanName);
		// 檢查所有的 bean 是否是 SmartInitializingSingleton 接口
		if (singletonInstance instanceof SmartInitializingSingleton) {
			final SmartInitializingSingleton smartSingleton = (SmartInitializingSingleton) singletonInstance;
			if (System.getSecurityManager() != null) {
				AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
					smartSingleton.afterSingletonsInstantiated();
					return null;
				}, getAccessControlContext());
			}
			else {
				// 回調 afterSingletonsInstantiated() 方法,可以在回調中做一些事情
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}           

釋出BeanFactory容器重新整理完成事件

org.springframework.context.support.AbstractApplicationContext#finishRefresh:

整個容器初始化完畢之後,會在這裡進行一些掃尾工作,如清理緩存,初始化生命周期處理器,釋出容器重新整理事件等。

protected void finishRefresh() {
	// Clear context-level resource caches (such as ASM metadata from scanning).
	// 清理緩存
	clearResourceCaches();
 
	// Initialize lifecycle processor for this context.
	// 初始化和生命周期有關的後置處理器
	initLifecycleProcessor();
 
	// Propagate refresh to lifecycle processor first.
	// 拿到前面定義的生命周期處理器【LifecycleProcessor】回調 onRefresh() 方法
	getLifecycleProcessor().onRefresh();
 
	// Publish the final event.
	// 釋出容器重新整理完成事件
	publishEvent(new ContextRefreshedEvent(this));
 
	// Participate in LiveBeansView MBean, if active.
	LiveBeansView.registerApplicationContext(this);
}           
Spring容器啟動流程

總的來說:

IoC(Inverse of Control:控制反轉)是一種設計思想,就是 将原本在程式中手動建立對象的控制權,交由Spring架構來管理。 IoC 在其他語言中也有應用,并非 Spirng 特有。

另一方面了解IOC就是容器, IOC 容器實際上就是個Map(key,value), Map 中存放的是各種對象,采用三級緩存的方式管理不通狀态下的對象,從建立到銷毀的整個bean的生命周期都是由容器來管理。

IOC容器建立過程大緻是這樣的:

  1. 執行個體化BeanFactory【DefaultListableBeanFactory】工廠,用于生成Bean對象。執行個體化BeanDefinitionReader bean定義資訊讀取器,加載解析bean對象,建立bean對象的定義資訊BeanDefinition。
  2. prepareBeanFactory(beanFactory) BeanFactory的預處理,這個接口是為 beanFactory 工廠添加一些内置元件,預處理過程。
  3. 執行beanFactory的後置處理器,像PlaceholderConfigurerSupport