Spring源碼之ApplicationContext

本文是針對Srping的ClassPathXMLApplicationContext來進行源碼解析,在本篇博客中將不會講述spring Xml解析註冊代碼,由於ApplicationContext是BeanFactory的擴展版本,ApplicationContext的GetBean和xml解析註冊BeanDefinition都是用一套代碼,若是您是第一次看請先看一下XMLBeanFactory解析和BeanFactory.GetBean源碼解析:html

做者整理了spring-framework 5.x的源碼註釋,代碼已經上傳者做者的GitHub了,可讓讀者更好的理解,地址:git

  • 接下來咱們你直接上源碼:
package lantao;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.lantao.UserBean;

public class ApplicationContextTest {

	public static void main(String[] args) {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-bean.xml");
		UserBean userBean = (UserBean) applicationContext.getBean("userBean");
		System.out.println(userBean.getName());
	}

}
複製代碼

在這裏直接使用ClassPathXmlApplicationContext進行xml解析,在這裏xml解析的代碼和GetBean的代碼就不過多的描述了,ApplicationContext是BeanFactory的擴展,因此想要看這兩部分源碼的請看做者的上兩篇博客Sprin源碼解析; github

  • 接下來咱們看一下ClassPathXmlApplicationContext的源碼:
/**
 * Create a new ClassPathXmlApplicationContext with the given parent,
 * loading the definitions from the given XML files.
 * @param configLocations array of resource locations
 * @param refresh whether to automatically refresh the context,
 * loading all bean definitions and creating all singletons.
 * Alternatively, call refresh manually after further configuring the context.
 * @param parent the parent context
 * @throws BeansException if context creation failed
 * @see #refresh()
 */
public ClassPathXmlApplicationContext(
		String[] configLocations, boolean refresh, @Nullable ApplicationContext parent)
		throws BeansException {

	super(parent);
	// 支持解析多文件
	setConfigLocations(configLocations);
	if (refresh) {
		refresh();
	}
}複製代碼

在setConfigLocations方法中將資源文件放入configLocations全局變量中,,而且支持多文件解析,接下來咱們你看一下重點,refresh方法;spring

  • 源碼refresh方法:
@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的各類功能填充,加載beanFactory,通過這個方法 applicationContext就有了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.
			//  容許在context子類中對BeanFactory進行post-processing。
			// 容許在上下文子類中對Bean工廠進行後處理
			// 能夠在這裏進行 硬編碼形式的 BeanFactoryPostProcessor 調用 addBeanFactoryPostProcessor
			postProcessBeanFactory(beanFactory);

			// Invoke factory processors registered as beans in the context.
			// 激活各類BeanFactory處理器 BeanFactoryPostProcessors是在實例化以前執行
			invokeBeanFactoryPostProcessors(beanFactory);

			// Register bean processors that intercept bean creation.
			// 註冊 攔截Bean建立 的Bean處理器,這裏只是註冊,真正地調用在getBean的時候  BeanPostProcessors實在init方法先後執行 doCreateBean方法中的 實例化方法中執行
			// BeanPostProcessor執行位置:doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization
			registerBeanPostProcessors(beanFactory);

			// Initialize message source for this context.
			//爲上下文初始化Message源,(好比國際化處理) 這裏沒有過多深刻
			initMessageSource();

			// Initialize event multicaster for this context.
			//初始化應用消息廣播,並放入 applicationEventMulticaster bean中
			initApplicationEventMulticaster();

			// Initialize other special beans in specific context subclasses.
			//留給子類來初始化其它的bean
			onRefresh();

			// Check for listener beans and register them.
			//在全部註冊的bean中查找Listener bean,註冊到消息廣播器中
			registerListeners();

			// Instantiate all remaining (non-lazy-init) singletons.
			//初始化剩下的單實例
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			//完成刷新過程,通知生命週期護處理器lifecycleProcessor刷新過程,同時發出ContextRefreshEvent通知別人(LifecycleProcessor 用來與全部聲明的bean的週期作狀態更新)
			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(); } } }複製代碼

對於ApplicationContext來講,refresh方法幾乎涵蓋了全部的基礎和擴展功能,接下來看一下這個方法都作了什麼;bash

  1. 刷新上下文,初始化前的準備工做;
  2. 加載beanFactory,通過這個方法 applicationContext就有了BeanFactory的全部功能
  3. 對beanFactory進行各類功能填充
  4. 容許在這裏對BeanFactory的二次加工,例如:能夠在這裏進行硬編碼方法的對BeanFactory進行BeanFactoryPostProcessor或BeanPostProcessor的操做;在這裏簡單說一下BeanFactoryPostProcessor是在bean實例化以前執行的,BeanPostProcessor是在初始化方法先後執行的,BeanFactoryPostProcessor操做的是BeanFactoryBeanPostProcessor操做的是Bean,其次這裏還涉及了一個擴展BeanDefinitionRegistryPostProcessor它是繼承了BeanFactoryPostProcessor,而且還有本身的定義方法 postProcessBeanDefinitionRegistry,這個方法能夠操做BeanDefinitionRegistry,BeanDefinitionRegistry有個最主要的方法就是registerBeanDefinition,能夠註冊BeanDefinition,能夠用這方法來處理一下不受spring管理的一下bean;
  5. 處理全部的BeanFactoryPostProcessor,也能夠說是激活BeanFactory處理器,在這個方法裏會先處理BeanDefinitionRegistryPostProcessor,在處理BeanFactoryPostProcessor,由於BeanDefinitionRegistryPostProcessor有本身的定義,因此先執行;
  6. 註冊BeanPostProcessors ,這裏只是註冊,真正地調用在getBean的時候 BeanPostProcessors實在init方法先後執行 BeanPostProcessor執行位置:doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization方法中;
  7. 爲上下文初始化Message源,(好比國際化處理) 這裏沒有過多深刻;
  8. 初始化應用消息廣播,初始化 applicationEventMulticaster ,判斷使用自定義的仍是默認的;
  9. 留給子類來初始化其它的bean;
  10. 在全部註冊的bean中查找 ApplicationListener bean,註冊到消息廣播器中;
  11. 初始化剩下的單實例(非懶加載),這裏會是涉及conversionService,LoadTimeWeaverAware,凍結BeanFactory,初始化Bean等操做;
  12. 完成刷新過程,包括 清除 下文級資源(例如掃描的元數據),通知生命週期護處理器lifecycleProcessor並strat,同時publish Event發出ContextRefreshEvent通知別人;
  • 先來看prepareRefresh方法:
/**
 * Prepare this context for refreshing, setting its startup date and
 * active flag as well as performing any initialization of property sources.
 */
protected void prepareRefresh() {
	// Switch to active.
	this.startupDate = System.currentTimeMillis();
    // 標誌,指示是否已關閉此上下文
	this.closed.set(false);
    // 指示此上下文當前是否處於活動狀態的標誌
	this.active.set(true);

	if (logger.isDebugEnabled()) {
		if (logger.isTraceEnabled()) {
			logger.trace("Refreshing " + this);
		}
		else {
			logger.debug("Refreshing " + getDisplayName());
		}
	}

	// Initialize any placeholder property sources in the context environment.
	// 對上下文環境中的任何屬性源進行分類。
	initPropertySources();

	// Validate that all properties marked as required are resolvable:
	// see ConfigurablePropertyResolver#setRequiredProperties,

	//驗證標示爲必填的屬性信息是否都有了 ConfigurablePropertyResolver#setRequiredProperties 方法
	getEnvironment().validateRequiredProperties();

	// Store pre-refresh ApplicationListeners...
	if (this.earlyApplicationListeners == null) {
		this.earlyApplicationListeners = new LinkedHashSet<>(this.applicationListeners);
	}
	else {
		// Reset local application listeners to pre-refresh state.
		this.applicationListeners.clear();
		this.applicationListeners.addAll(this.earlyApplicationListeners);
	}

	// Allow for the collection of early ApplicationEvents,
	// to be published once the multicaster is available...
	this.earlyApplicationEvents = new LinkedHashSet<>();
}複製代碼

一眼望去,可能以爲這個方法沒有作什麼,其實這方法中除了Closed和Active最終要的是initPropertySources和getEnvironment().validateRequiredProperties()方法;app

  1. initPropertySources證符合Spring的開放式結構設計,給用戶最大擴展Spring的能力。用戶能夠根據自身的須要重寫initPropertySourece方法,並在方法中進行個性化的屬性處理及設置。
  2. validateRequiredProperties則是對屬性進行驗證,那麼如何驗證呢?舉個融合兩句代碼的小例子來理解。

例如如今有這樣一個需求,工程在運行過程當中用到的某個設置(例如VAR)是從系統環境變量中取得的,而若是用戶沒有在系統環境變量中配置這個參數,工程不會工做。這一要求也各類各樣許有的解決辦法,在Spring中能夠這麼作,能夠直接修改Spring的源碼,例如修改ClassPathXmlApplicationContext.淡然,最好的辦法是對源碼進行擴展,能夠自定義類:編輯器

public class MyClassPathXmlApplicationContext extends ClassPathXmlApplicationContext{
      public MyClassPathXmlApplicationContext(String.. configLocations){
            super(configLocations);
       }
       protected void initPropertySources(){
             //添加驗證要求
             getEnvironment().setRequiredProterties("VAR");
       }
}複製代碼

自定義了繼承自ClassPathXmlApplicationContext的MyClassPathXmlApplicationContext,並重寫了initPropertySources方法,在方法中添加了個性化需求,那麼在驗證的時候也就是程序走到getEnvironment().validateRequiredProperties()代碼的時候,若是系統並無檢測到對應VAR的環境變量,將拋出異常。固然咱們還須要在使用的時候替換掉原有的ClassPathXmlApplicationContext:ide

public static void main(Stirng[] args){
      ApplicationContext bf = new MyClassPathXmlApplicationContext("myTest.xml");
      User user = (User)bf.getBean("testBean");
}複製代碼

上述案例來源於:Spring源碼深度解析(第二版)141頁;

  • 接下來看一下obtainFreshBeanFactory方法,在這裏初始化DefaultListAbleBeanFactory並解析xml:
/**
 * Tell the subclass to refresh the internal bean factory.
 * @return the fresh BeanFactory instance
 * @see #refreshBeanFactory()
 * @see #getBeanFactory()
 */
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	return getBeanFactory();
}複製代碼
/**
 * This implementation performs an actual refresh of this context's underlying * bean factory, shutting down the previous bean factory (if any) and * initializing a fresh bean factory for the next phase of the context's lifecycle.
 */
@Override
protected final void refreshBeanFactory() throws BeansException {
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
		// createBeanFactory方法直接新建一個DefaultListableBeanFactory,內部使用的是DefaultListableBeanFactory實例
		DefaultListableBeanFactory beanFactory = createBeanFactory();
		// 設置序列化id
		beanFactory.setSerializationId(getId());
		// 定製beanFactory工廠
		customizeBeanFactory(beanFactory);
		// 加載BeanDefinition
		loadBeanDefinitions(beanFactory);
		synchronized (this.beanFactoryMonitor) {
			// 使用全局變量記錄BeanFactory
			this.beanFactory = beanFactory;
		}
	}
	catch (IOException ex) {
		throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
	}
}複製代碼

看一下上述方法都作了什麼:工具

  1. 判斷BeanFactory是否存在,若是存在則銷燬全部Bean,而後關閉BeanFactory;
  2. 使用createBeanFactory方法直接新建一個DefaultListableBeanFactory,內部使用的是DefaultListableBeanFactory實例;
  3. 設置BeanFactory的設置序列化id
  4. 定製beanFactory工廠,也就是給allowBeanDefinitionOverriding(是否容許覆蓋同名稱的Bean)和allowCircularReferences(是否容許bean存在循環依賴),可經過setAllowBeanDefinitionOverriding和setAllowCircularReferences賦值,這裏就可經過商編初始化方法中的initPropertySources方法來進行賦值;
  5. package lantao;
    
    import org.springframework.context.support.ClassPathXmlApplicationContext;
    
    public class MyApplicationContext extends ClassPathXmlApplicationContext {
    
    	public MyApplicationContext(String... configLocations){
    		super(configLocations);
    	}
    	protected void initPropertySources(){
    		//添加驗證要求
    		getEnvironment().setRequiredProperties("VAR");
    
                    // 在這裏添加set
    		super.setAllowBeanDefinitionOverriding(true);
    		super.setAllowCircularReferences(true);
    	}
    }
    複製代碼


  6. 加載BeanDefinition,就是解析xml,循環解析,這裏就不看了,若是不瞭解看做者上篇博客;
  • 下面看一下prepareBeanFactory方法源碼:
/**
 * Configure the factory's standard context characteristics, * such as the context's ClassLoader and post-processors.
 * @param beanFactory the BeanFactory to configure
 */
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc. // 設置BeanFactory的classLoader爲當前context的classloader beanFactory.setBeanClassLoader(getClassLoader()); // Spel語言解析器 // 設置BeanFactory的表達式語言處理器 Spring3中增長了表達式語言的支持 // 默承認以使用#{bean.xxx}的形式來調用相關屬性值 // 在Bean實例化的時候回調用 屬性填充的方法(doCreateBean 方法中的 populateBean 方法中的 applyPropertyValues 方法中的 evaluateBeanDefinitionString ) 就會判斷beanExpressionResolver是否爲null操做 beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader())); // 爲BeanFactory增長一個默認的 PropertyEditor 這個主要對bean的屬性等設置管理的一個工具 增長屬性註冊編輯器 例如:bean property 類型 date 則須要這裏 // beanFactory會在初始化 BeanWrapper(initBeanWrapper)中調用 ResourceEditorRegistrar 的 registerCustomEditors 方法 beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment())); // Configure the bean factory with context callbacks. // ApplicationContextAwareProcessor --> postProcessBeforeInitialization // 註冊 BeanPostProcessor BeanPostProcessor 實在實例化先後執行的 beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this)); // 設置幾個忽略自動裝配的接口 在addBeanPostProcessor方法中已經對下面幾個類作了處理,他們就不是普通的bean了,因此在這裏spring作bean的依賴的時候忽略 // doCreateBean 方法中的 populateBean 方法中的 autowireByName 或 autowireByType 中的 unsatisfiedNonSimpleProperties 中的 !isExcludedFromDependencyCheck(pd) 判斷, // 在屬性填充的時候回判斷依賴,若是存在下屬幾個則不作處理 對於下面幾個類能夠作implements操做 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. // 設置幾個註冊依賴 參考spring源碼深度解析原文:當註冊依賴解析後,例如但那個註冊了對BeanFactory。class的解析依賴後,當bean的屬性注入的時候,一旦檢測到屬性爲BeanFactory的類型變回將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. // 寄存器早期處理器,用於檢測做爲ApplicationListener的內部bean。 beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(this)); // Detect a LoadTimeWeaver and prepare for weaving, if found. // 增長了對AxpectJ的支持 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. // 添加默認的系統環境bean 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()); } }複製代碼

不說廢話,直接看這個方法都作了什麼:post

  1. 設置BeanFactory的classLoader爲當前context的classloader;
  2. 設置BeanFactory的表達式語言處理器 Spring3中增長了Spel表達式語言的支持, 默承認以使用#{bean.xxx}的形式來調用相關屬性值,在Bean實例化的時候回調用 屬性填充的方法(doCreateBean 方法中的 populateBean 方法中的 applyPropertyValues 方法中的 evaluateBeanDefinitionString ) 就會判斷beanExpressionResolver是否爲null操做,若是不是則會使用Spel表達式規則解析
    <?xml version="1.0" encoding="UTF-8" ?>
    <beans
           xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
    
    	<bean id="testOneBean" class="lantao.bean.TestOneBean">
    		<property name="testTwoBean" value="#{testTWoBean}"/>
    	</bean>
    	
    	<bean id="testTWoBean" class="lantao.bean.TestTwoBean"/>
    
    	<!-- 上面 至關於 下邊 -->
    
    	<bean id="testOneBean1" class="lantao.bean.TestOneBean">
    		<property name="testTwoBean" ref="testTWoBean1"/>
    	</bean>
    
    	<bean id="testTWoBean1" class="lantao.bean.TestTwoBean"/>
    
    </beans>複製代碼
  3. 爲BeanFactory增長一個默認的 PropertyEditor 這個主要對bean的屬性等設置管理的一個工具 增長屬性註冊編輯器 例如:User類中 startDate 類型 date 可是xml property的value是2019-10-10,在啓動的時候就會報錯,類型轉換不成功,這裏可使用繼承PropertyEditorSupport這個類機型重寫並注入便可使用;beanFactory會在初始化BeanWrapper (initBeanWrapper)中調用 ResourceEditorRegistrar 的 registerCustomEditors 方法進行初始化;
  4. 配置BeanPostProcessor,這裏配置的是ApplicationContextAwareProcessor,上邊咱們說了,BeanPostProcessor是在初始化方法Init先後執行,看一下ApplicationContextAwareProcessor的Before和After方法:
    @Override
    @Nullable
    public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
    	AccessControlContext acc = null;
    
    	// 該方法也會在 BeanFactory 實例化bean 中調用  doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization --> postProcessBeforeInitialization
    	// 若是實例化的類實現了 invokeAwareInterfaces 方法中的判斷類 則會調用初始方法賦值
    	if (System.getSecurityManager() != null &&
    			(bean instanceof EnvironmentAware || bean instanceof EmbeddedValueResolverAware ||
    					bean instanceof ResourceLoaderAware || bean instanceof ApplicationEventPublisherAware ||
    					bean instanceof MessageSourceAware || bean instanceof ApplicationContextAware)) {
    		acc = this.applicationContext.getBeanFactory().getAccessControlContext();
    	}
    
    	if (acc != null) {
    		AccessController.doPrivileged((PrivilegedAction<Object>) () -> {
    			invokeAwareInterfaces(bean);
    			return null;
    		}, acc);
    	}
    	else {
    		invokeAwareInterfaces(bean);
    	}
    		return bean;
    }
    private void invokeAwareInterfaces(Object bean) {
    	if (bean instanceof Aware) {
    		if (bean instanceof EnvironmentAware) {
    			((EnvironmentAware) bean).setEnvironment(this.applicationContext.getEnvironment());
    		}
    		if (bean instanceof EmbeddedValueResolverAware) {
    			((EmbeddedValueResolverAware) bean).setEmbeddedValueResolver(this.embeddedValueResolver);
    		}
    		if (bean instanceof ResourceLoaderAware) {
    			((ResourceLoaderAware) bean).setResourceLoader(this.applicationContext);
    		}
    		if (bean instanceof ApplicationEventPublisherAware) {
    			((ApplicationEventPublisherAware) bean).setApplicationEventPublisher(this.applicationContext);
    		}
    		if (bean instanceof MessageSourceAware) {
    			((MessageSourceAware) bean).setMessageSource(this.applicationContext);
    		}
    		if (bean instanceof ApplicationContextAware) {
    			((ApplicationContextAware) bean).setApplicationContext(this.applicationContext);
    		}
    	}
    }
    
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) {
    	return bean;
    }
    複製代碼

    在Before方法中調用了invokeAwareInterfaces方法,在invokeAwareInterfaces方法中作了類型 instanceof 的判斷,意思就是若是這個Bean實現了上述的Aware,則會初始會一下資源,好比實現了ApplicationContextAware,就會setApplicationContext,這裏相信你們都用過,就很少說了;

  5. 設置幾個忽略自動裝配的接口 在addBeanPostProcessor方法中已經對下面幾個類作了處理,他們就不是普通的bean了,因此在這裏spring作bean的依賴的時候忽略,在doCreateBean 方法中的 populateBean 方法中的 autowireByName 或 autowireByType 中的 unsatisfiedNonSimpleProperties 中的 !isExcludedFromDependencyCheck(pd) 判斷,若是存在則不作依賴注入了;
  6. 設置幾個註冊依賴 參考spring源碼深度解析原文:當註冊依賴解析後,例如當註冊了對BeanFactory的解析依賴後,當bean的屬性注入的時候,一旦檢測到屬性爲BeanFactory的類型便會將beanFactory 實例注入進去;
  7. 添加BeanPostProcessor,這裏是添加ApplicationListener,是寄存器早期處理器;這裏能夠看做者的源碼測試,在spring-context的test測試類下有;
  8. 增長了對AxpectJ的支持
  9. 註冊默認的系統環境bean,environment ,systemProperties,systemEnvironment;
  • 上述就是對BeanFactory的功能填充,下面看postProcessBeanFactory:

postProcessBeanFactory方法是個空方法,容許在上下文子類中對Bean工廠進行後處理,例如:能夠在這裏進行 硬編碼形式的 BeanFactoryPostProcessor 調用 addBeanFactoryPostProcessor,進行addBeanFactoryPostProcessor或者是BeanPostProcessor;

  • 接下來看一下invokeBeanFactoryPostProcessors方法:
public static void invokeBeanFactoryPostProcessors(
		ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {

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

	// 對 BeanDefinitionRegistry  類型處理
	if (beanFactory instanceof BeanDefinitionRegistry) {
		// 強轉
		BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

		// 普通的處理器
		List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();

		//註冊處理器
		List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();


		// 這裏就是硬編碼處理 由於這裏是從 getBeanFactoryPostProcessors()方法獲取的 能夠硬編碼從addBeanFactoryPostProcessor()方法添加
		for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {

			if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {

				// 對於 BeanDefinitionRegistryPostProcessor 類型 在 BeanFactoryPostProcessor 的基礎上還有本身的定義,須要先調用
				BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;

				// 執行 繼承 BeanDefinitionRegistryPostProcessor 類的  postProcessBeanDefinitionRegistry 方法
				registryProcessor.postProcessBeanDefinitionRegistry(registry);

				registryProcessors.add(registryProcessor);
			}
			else {
				regularPostProcessors.add(postProcessor);
			}
		}
		//上邊的For循環只是調用了硬編碼的 BeanDefinitionRegistryPostProcessor 中的 postProcessBeanDefinitionRegistry 方法,
		// 可是 BeanFactoryPostProcessor 中的 postProcessBeanFactory 方法尚未調用,是在方法的最後一行
		// invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		// invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory); 這兩個方法中執行的,


		// 下面是自動處理器 獲取類型是BeanDefinitionRegistryPostProcessor  beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false); 獲取的


		// 當前註冊處理器
		List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();

		// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
		// 首先調用實現了 PriorityOrdered 的 BeanDefinitionRegistryPostProcessors
		String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);

		for (String ppName : postProcessorNames) {
			if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		// 執行 BeanDefinitionRegistryPostProcessor類的postProcessBeanDefinitionRegistry方法
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		currentRegistryProcessors.clear();

		// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
		// 下一個 ,調用實現 Ordered 的 BeanDefinitionRegistryPostProcessors
		postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
		for (String ppName : postProcessorNames) {
			if (!processedBeans.contains(ppName) && beanFactory.isTypeMatch(ppName, Ordered.class)) {
				currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
				processedBeans.add(ppName);
			}
		}
		sortPostProcessors(currentRegistryProcessors, beanFactory);
		registryProcessors.addAll(currentRegistryProcessors);
		// 執行 BeanDefinitionRegistryPostProcessor類的postProcessBeanDefinitionRegistry方法
		invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
		currentRegistryProcessors.clear();

		// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
		// 最後,調用全部其餘BeanDefinitionRegistryPostProcessors,直到再也不顯示其餘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);
			// 執行 BeanDefinitionRegistryPostProcessor類的postProcessBeanDefinitionRegistry方法
				invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
				currentRegistryProcessors.clear();
		}

		// 如今,調用到目前爲止處理的全部處理器的  執行BeanFactoryPostProcessor 類的 postProcessBeanFactory 方法
		// 這裏執行的是 硬編碼 和 非硬編碼(自動)的 BeanFactoryPostProcessor 類的 postProcessBeanFactory 方法 分爲硬編碼處理器 和 普通處理器
		invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
		invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
	}

	else {
		// 調用在上下文實例中註冊的工廠處理器的postProcessBeanFactory方法。 就是硬編碼 經過 addBeanFactoryPostProcessor 方法添加的BeanFactoryPostProcessor
			invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
	}




	// 自動處理 非硬編碼 獲取類型爲是BeanFactoryPostProcessor    beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);

	// 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.

	//  實現 priorityOrdered 的
	List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();

	// 實現 Ordered 的
	List<String> orderedPostProcessorNames = new ArrayList<>();

	// 無序的
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();

	for (String ppName : postProcessorNames) {
		if (processedBeans.contains(ppName)) {
			// skip - already processed in first phase above
		}
		else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

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

	// 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.
	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();
}
複製代碼

上述代碼看起來不少,可是總計起來就三件事:

  1. 執行硬編碼的和主動注入的BeanDefinitionRegistryPostProcessor,調用postProcessBeanDefinitionRegistry方法;
  2. 執行硬編碼的和主動注入的BeanFactoryPostProcessor,調用postProcessBeanFactory方法;
  3. 自動注入的可繼承Ordered排序,priorityOrdered排序或無序;

上述測試在做者的spring源碼congtext中lantao包下有測試用例;

  • registerBeanPostProcessors方法源碼:
public static void registerBeanPostProcessors(
		ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {

	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;
	beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));

	// Separate between BeanPostProcessors that implement PriorityOrdered,
	// Ordered, and the rest.
	// 使用 priorityOrdered保證順序
	List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();

	// MergedBeanDefinitionPostProcessor
	List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();

	// 使用order保證順序
	List<String> orderedPostProcessorNames = new ArrayList<>();

	// 無序的
	List<String> nonOrderedPostProcessorNames = new ArrayList<>();

	// 進行add操做
	for (String ppName : postProcessorNames) {
		if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
			BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
			priorityOrderedPostProcessors.add(pp);
			if (pp instanceof MergedBeanDefinitionPostProcessor) {
				internalPostProcessors.add(pp);
			}
		}
		else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
			orderedPostProcessorNames.add(ppName);
		}
		else {
			nonOrderedPostProcessorNames.add(ppName);
		}
	}

	// First, register the BeanPostProcessors that implement PriorityOrdered.
	// 首先 註冊實現PriorityOrdered的 BeanPostProcessors 先排序PostProcessors
	sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
	registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);

	// Next, register the BeanPostProcessors that implement Ordered.
	// 下一個,註冊實現Ordered的BeanPostProcessors
	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);
		}
	}
	sortPostProcessors(orderedPostProcessors, beanFactory);
	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);
		}
	}
	registerBeanPostProcessors(beanFactory, nonOrderedPostProcessors);

	// Finally, re-register all internal BeanPostProcessors.
	// 最後,註冊全部MergedBeanDefinitionPostProcessor類型的BeanPostProcessor,並不是重複註冊。
	sortPostProcessors(internalPostProcessors, beanFactory);
	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).
	// 添加 ApplicationListener探測器
	beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}複製代碼

registerBeanPostProcessors方法代碼仍是比較長的,它和invokeBeanFactoryPostProcessors方法最主要的區別就是registerBeanPostProcessors只在這裏註冊,但不在這裏調用,作的事情和invokeBeanFactoryPostProcessors差很少:

  1. 使用priorityOrdered,Ordered或無序保證順序;
  2. 經過beanFactory.addBeanPostProcessor(postProcessor)進行註冊;

很簡單,代碼篇幅很長,可是很好理解,這裏能夠簡單看一下;


  • 接下來是initMessageSource方法,這裏做者沒有過多的看源碼,後續補上吧.......(抱歉)


  • initApplicationEventMulticaster源碼:
/**
 * Initialize the ApplicationEventMulticaster.
 * Uses SimpleApplicationEventMulticaster if none defined in the context.
 * @see org.springframework.context.event.SimpleApplicationEventMulticaster
 */
protected void initApplicationEventMulticaster() {
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	// 使用自定義的 廣播
	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 {
		// 使用spring 默認的廣播
		this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(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() + "]");
		}
	}
}
複製代碼

initApplicationEventMulticaster方法中主要就是判斷是使用自定義的ApplicationEventMulticaster(廣播器)仍是使用呢Spring默認的SimpleApplicationEventMulticaster廣播器;


  • onRefresh 方法是留個子類重寫的,內容是空;


  • registerListeners方法:
/**
 * Add beans that implement ApplicationListener as listeners.
 * Doesn't affect other listeners, which can be added without being beans. */ protected void registerListeners() { // Register statically specified listeners first. // 註冊 添加 ApplicationListener 這裏經過硬編碼 addApplicationListener 方法添加的 for (ApplicationListener<?> listener : getApplicationListeners()) { 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... // 發佈早期的事件 Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents; this.earlyApplicationEvents = null; if (earlyEventsToProcess != null) { for (ApplicationEvent earlyEvent : earlyEventsToProcess) { getApplicationEventMulticaster().multicastEvent(earlyEvent); } } }複製代碼

registerListeners方法作了三件事情:

  1. 添加 ApplicationListener 這裏經過硬編碼 addApplicationListener 方法添加的;
  2. 添加 ApplicationListener 是經過自動註冊添加的
  3. 發佈早起事件
  • finishBeanFactoryInitialization方法源碼:
/**
 * Finish the initialization of this context's bean factory, * initializing all remaining singleton beans. */ protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) { // Initialize conversion service for this context. // conversionService 用於類型轉換 ,好比 String 轉Date //判斷BeanFactory中是否存在名稱爲「conversionService」且類型爲ConversionService的Bean,若是存在則將其注入到beanFactory // 判斷有無自定義屬性轉換服務接口,並將其初始化,咱們在分析bean的屬性填充過程當中,曾經用到過該服務接口。在TypeConverterDelegate類的convertIfNecessary方法中 if (beanFactory.containsBean(CONVERSION_SERVICE_BEAN_NAME) && beanFactory.isTypeMatch(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)) { beanFactory.setConversionService( beanFactory.getBean(CONVERSION_SERVICE_BEAN_NAME, ConversionService.class)); } // Register a default embedded value resolver if no bean post-processor // (such as a PropertyPlaceholderConfigurer bean) registered any before: // at this point, primarily for resolution in annotation attribute values. if (!beanFactory.hasEmbeddedValueResolver()) { beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal)); } // Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early. // 獲得全部的實現了LoadTimeWeaverAware接口的子類名稱,初始化它們 // 若是有LoadTimeWeaverAware類型的bean則初始化,用來加載Spring Bean時織入第三方模塊,如AspectJ,咱們在後面詳細講解。 String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false); for (String weaverAwareName : weaverAwareNames) { getBean(weaverAwareName); } // Stop using the temporary ClassLoader for type matching. // 中止使用臨時類加載器 就是在這裏不讓使用呢 ClassLoader 了 beanFactory.setTempClassLoader(null); // Allow for caching all bean definition metadata, not expecting further changes. // 凍結全部bean定義,說明你註冊的bean將不被修改或進行任何進一步的處理 就是不讓改了 BeanDefinition beanFactory.freezeConfiguration(); // Instantiate all remaining (non-lazy-init) singletons. // 初始化全部非懶加載的 單例 bean 調用你getBean方法 beanFactory.preInstantiateSingletons(); } 複製代碼

finishBeanFactoryInitialization方法作了五件事情:

  1. 設置BeanFactory的conversionService,conversionService用於類型轉換使用, 例如:User類中 startDate 類型 date 可是xml property的value是2019-10-10,在啓動的時候就會報錯,類型轉換不成功,可使用conversionService;書中170頁有具體代碼;
  2. 添加BeanFactory的addEmbeddedValueResolver,讀取配置信息放到這裏,能夠經過EmbeddedValueResolverAware來獲取,參考:www.cnblogs.com/winkey4986/…
  3. 獲得全部的實現了LoadTimeWeaverAware接口的子類名稱,初始化它們,用來加載Spring Bean時織入第三方模塊,如AspectJ,咱們在後面詳細講解。
  4. 中止使用臨時類加載器 就是在這裏不讓使用呢 ClassLoader 了
  5. 凍結全部bean定義,說明你註冊的bean將不被修改或進行任何進一步的處理 就是不讓改了 BeanDefinition
  6. 初始化全部非懶加載的 單例 bean 調用你getBean方法,循環全部bean並實例化 條件是:單例,非Abstract 非懶加載
  • 最後的一個方法finishRefresh:
/**
 * Finish the refresh of this context, invoking the LifecycleProcessor's * onRefresh() method and publishing the * {@link org.springframework.context.event.ContextRefreshedEvent}. */ protected void finishRefresh() { // Clear context-level resource caches (such as ASM metadata from scanning). // 清除 下文級資源(例如掃描的元數據)。 clearResourceCaches(); // Initialize lifecycle processor for this context. // 在當前context中初始化 lifecycle // lifecycle 有本身的 start/ stop方法,實現此接口後spring保證在啓動的時候調用start方法開始生命週期 關閉的時候調用 stop方法結束生命週期 initLifecycleProcessor(); // Propagate refresh to lifecycle processor first. // onRefresh 啓動全部實現了 lifecycle 的方法 getLifecycleProcessor().onRefresh(); // Publish the final event. // 當ApplicationContext初始化完成發佈後發佈事件 處理後續事宜 publishEvent(new ContextRefreshedEvent(this)); // Participate in LiveBeansView MBean, if active. // 這裏 沒明白》。。 LiveBeansView.registerApplicationContext(this); } 複製代碼

finishRefresh方法是ApplicationContext初始化的最後一個方法了,他作了一些結尾的事情:

  1. 清除 下文級資源(例如掃描的元數據)。
  2. 在當前context中初始化 lifecycle,lifecycle 有本身的 start/ stop方法,實現此接口後spring保證在啓動的時候調用start方法開始生命週期 關閉的時候調用 stop方法結束生命週期。
  3. onRefresh 啓動全部實現了 lifecycle 的方法,調用了start方法。
  4. 當ApplicationContext初始化完成發佈事件 處理後續事宜。
  5. LiveBeansView.registerApplicationContext(this)這個代碼沒有太明白,有大神能夠留言;

至此ApplicationContext的源碼就都已經分析完成了,其中有不少地方很難懂,你們能夠對應着源碼一塊兒看,會好理解一些,若是其中有錯誤,歡迎大神指點,在下方留言,本篇博客是做者參考SPring 源碼深度解析 + 本身的理解寫出來的,算是一個學習後的的產出,最後,碼字不易,轉載請註明出處。 

地址:https://juejin.im/editor/drafts/5c8c8174f265da2db912b519 或 https://mp.csdn.net/postedit/88224879

相關文章
相關標籤/搜索