Spring源碼-IOC容器(七)-ApplicationContext

Spring IOC容器 源碼解析系列,建議你們按順序閱讀,歡迎討論web

(spring源碼均爲4.1.6.RELEASE版本)spring

  1. Spring源碼-IOC容器(一)-構建簡單IOC容器
  2. Spring源碼-IOC容器(二)-Bean的定位解析註冊
  3. Spring源碼-IOC容器(三)-GetBean
  4. Spring源碼-IOC容器(四)-FactoryBean
  5. Spring源碼-IOC容器(五)-Bean的初始化
  6. Spring源碼-IOC容器(六)-bean的循環依賴
  7. Spring源碼-IOC容器(七)-ApplicationContext
  8. Spring源碼-IOC容器(八)-NamespaceHandler與自定義xml
  9. Spring源碼-IOC容器(九)-Component-Scan源碼解析
  10. Spring源碼-IOC容器(十)-@Autowired解析

ApplicationContext接口

在實際應用中使用Spring框架,大多數都不會使用BeanFactory的方式來構建Spring容器,由於Spring容器提供了一個更加簡易而強大的方式——ApplicationContext。ApplicationContext也是一個接口,不只繼承了BeanFactory的功能特性,並且支持了其餘高級容器的特性。先來看它的繼承結構:bootstrap

從繼承的接口能夠看出它支持了下面的幾個特性:app

  1. MessageSource,支持多消息源,主要用於主要用於國際化
  2. ApplicationEventPublisher,支持事件發佈,與Spring的生命週期相結合,更好地管理和擴展Spring
  3. ResourcePatternResolver,基類爲ResourceLoader,支持資源模式,更好地對各類方式(文件或I/O)定義的資源文件的處理
  4. EnvironmentCapable,對環境的感知

ApplicationContext自己提供的方法很是簡單,只定義了id和名稱的一些信息以及內部BeanFactory的get方法。框架

public interface ApplicationContext extends EnvironmentCapable, ListableBeanFactory, HierarchicalBeanFactory,
	MessageSource, ApplicationEventPublisher, ResourcePatternResolver {

// 惟一id
String getId();

// 所屬應用的名稱
String getApplicationName();

// 顯示名稱
String getDisplayName();

// 啓動時間
long getStartupDate();

// 父類ApplicationContext
ApplicationContext getParent();

// 內部BeanFactory
AutowireCapableBeanFactory getAutowireCapableBeanFactory() throws IllegalStateException;

}ide

ApplicationContext的實現類有不少,經常使用的有:函數

  • ClassPathXmlApplicationContext
  • FileSystemXmlApplicationContext
  • XmlWebApplicationContext

ClassPathXmlApplicationContext和FileSystemXmlApplicationContext只是加載資源文件的方式不一樣,而XmlWebApplicationContext是支持web項目,可是其底層的實現方式大部分都是一致的。下面就以經常使用的 ClassPathXmlApplicationContext來舉例分析Spring容器的啓動原理。post

ClassPathXmlApplicationContext實現原理

實際的項目中啓動一個Spring容器其實很簡單this

new ClassPathXmlApplicationContext("applicationcontext.xml");
CountDownLatch latch = new CountDownLatch(1);
latch.await();

首先建立ClassPathXmlApplicationContext對象,並傳入配置文件路徑,後面的兩句只是用來阻塞主進程結束的。來看ClassPathXmlApplicationContext的構造方法。編碼

public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
	this(new String[] {configLocation}, true, null);
}

public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
		throws BeansException {

	super(parent);
	setConfigLocations(configLocations);
	if (refresh) {
		refresh();
	}
}

super方法一直調用父類構造函數,直到AbstractApplicationContext抽象基類

public AbstractApplicationContext() {
	this.resourcePatternResolver = getResourcePatternResolver();
}

public AbstractApplicationContext(ApplicationContext parent) {
	this();
	setParent(parent);
}

this方法得到默認的資源解析器(ResourcePatternResolver),setParent方法設置父ApplicationContext,默認parent傳參爲null。

setConfigLocations方法將構造方法傳入的資源文件設置到AbstractRefreshableConfigApplicationContext方法的configLocations集合中。主要的操做refresh方法的實現是在AbstractApplicationContext類中。在refresh方法中,Spring抽象出每一個細分操做爲單獨的方法,而後按順序進行調用。具體來看源碼。

public void refresh() throws BeansException, IllegalStateException {
	synchronized (this.startupShutdownMonitor) {
		// Prepare this context for refreshing.
		// 刷新前準備,主要是設置開始時間以及標識active標誌位爲true
		prepareRefresh();

		// Tell the subclass to refresh the internal bean factory.
		// 建立BeanFactory實例,並加載配置文件
		ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();

		// Prepare the bean factory for use in this context.
		// BeanFactory準備工做,主要是設置類加載器,Spring表達式解析器以及框架相關的Aware接口默認配置
		prepareBeanFactory(beanFactory);

		try {
			// Allows post-processing of the bean factory in context subclasses.
			// BeanFactory後置處理(BeanFactory初始化完成後的擴展),如web項目中配置ServletContext
			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.
			// 爲特殊的上下文預留的方法,初始化特殊的bean
			onRefresh();

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

			// Instantiate all remaining (non-lazy-init) singletons.
			// 凍結全部配置並實例化全部非懶加載的單例bean
			finishBeanFactoryInitialization(beanFactory);

			// Last step: publish corresponding event.
			// 初始化生命週期,發佈容器事件
			finishRefresh();
		}

		catch (BeansException ex) {
			logger.warn("Exception encountered during context initialization - cancelling refresh attempt", ex);

			// Destroy already created singletons to avoid dangling resources.
			// 銷燬已經建立的單例bean
			destroyBeans();

			// Reset 'active' flag.
			// 重置active標識
			cancelRefresh(ex);

			// Propagate exception to caller.
			throw ex;
		}
	}
}

其實經過每一個子方法的名稱和註釋基本就能清楚其內部處理的主要內容,下面分析一些比較重要的節點方法。

建立組裝BeanFactory並加載資源文件

在ClassPathXmlApplicationContext構造方法中,定義的方法名爲refresh,就是指刷新,也就是Spring容器不只僅只是建立,也是能夠刷新的,而refresh方法中的obtainFreshBeanFactory方法顧名思義是得到一個新鮮的BeanFactory,它的實如今AbstractApplicationContext中。

protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
	refreshBeanFactory();
	ConfigurableListableBeanFactory beanFactory = getBeanFactory();
	if (logger.isDebugEnabled()) {
		logger.debug("Bean factory for " + getDisplayName() + ": " + beanFactory);
	}
	return beanFactory;
}

能夠看到,真正做用的是refreshBeanFactory,也就是真正對BeanFactory進行重置刷新的地方,而後refresh方法以後的操做基於一個新的BeanFactory進行組裝重建,從而達到刷新整個Spring容器的目的。refreshBeanFactory方法的實現是在AbstractApplicationContext的子類AbstractRefreshableApplicationContext中。

protected final void refreshBeanFactory() throws BeansException {
	// 若是已存在BeanFactory,則銷燬全部bean並關閉BeanFactory
	if (hasBeanFactory()) {
		destroyBeans();
		closeBeanFactory();
	}
	try {
		// 實例化一個新的BeanFactory
		DefaultListableBeanFactory beanFactory = createBeanFactory();
		// 設置序列化id爲惟一id
		beanFactory.setSerializationId(getId());
		// BeanFactory的自定義配置
		customizeBeanFactory(beanFactory);
		// 加載資源配置文件
		loadBeanDefinitions(beanFactory);
		synchronized (this.beanFactoryMonitor) {
			this.beanFactory = beanFactory;
		}
	}
	catch (IOException ex) {
		throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
	}
}

protected DefaultListableBeanFactory createBeanFactory() {
	return new DefaultListableBeanFactory(getInternalParentBeanFactory());
}

能夠看到默認建立的BeanFactory就是DefaultListableBeanFactory對象,以前的章節討論BeanFactory時也重點強調了這個類,至此發現它就是當前Spring容器內部BeanFactory的默認實現類。另外在此處對資源配置文件進行了加載,具體的加載方法同以前的章節大體相同,請見spring源碼-IOC容器(二)-Bean的定位解析註冊

BeanFactory建立完成後,須要對BeanFactory進行一些配置,提供對框架級操做的基礎。

protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
	// Tell the internal bean factory to use the context's class loader etc.
	// 類加載器
	beanFactory.setBeanClassLoader(getClassLoader());
	// Spring表達式解析器
	beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
	// 屬性編輯註冊器策略類
	beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));

	// Configure the bean factory with context callbacks.
	// 設置框架級Aware接口實現由容器自動注入對應屬性
	beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
	beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
	beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
	beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
	beanFactory.ignoreDependencyInterface(EnvironmentAware.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);

	// Detect a LoadTimeWeaver and prepare for weaving, if found.
	if (beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
		beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
		// Set a temporary ClassLoader for type matching.
		beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
	}

	// 註冊環境相關bean
	// Register default environment beans.
	if (!beanFactory.containsLocalBean(ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(ENVIRONMENT_BEAN_NAME, getEnvironment());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_PROPERTIES_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_PROPERTIES_BEAN_NAME, getEnvironment().getSystemProperties());
	}
	if (!beanFactory.containsLocalBean(SYSTEM_ENVIRONMENT_BEAN_NAME)) {
		beanFactory.registerSingleton(SYSTEM_ENVIRONMENT_BEAN_NAME, getEnvironment().getSystemEnvironment());
	}
}

實例化並執行BeanFactoryPostProcessor

BeanFactoryPostProcessor的定義是在BeanFactory初始化完成後對BeanFactory進行調整的擴展點。

public interface BeanFactoryPostProcessor {

	// 支持BeanFactory初始化完成後對其進行調整
	void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException;

}

而BeanDefinitionRegistryPostProcessor是BeanFactoryPostProcessor的子類,支持對BeanDefinition的調整。

public interface BeanDefinitionRegistryPostProcessor extends BeanFactoryPostProcessor {

	void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException;

}

來看refresh方法中執行BeanFactoryPostProcessor的具體子方法

protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
			PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
}

實際的操做是經過一個PostProcessor註冊委託類來處理,步驟以下:

  1. 對於內置的beanFactoryPostProcessors,判斷BeanFactory實現是否實現BeanDefinitionRegistry接口

      1. 過濾全部內置的beanFactoryPostProcessors中的BeanDefinitionRegistryPostProcessor
      2. 根據BeanDefinitionRegistryPostProcessor是否實現PriorityOrdered或Ordered接口進行排序,調用postProcessBeanDefinitionRegistry方法。優先執行PriorityOrdered接口的,其次爲Ordered,最後執行其餘的。
      3. 對沒有繼承BeanDefinitionRegistryPostProcessor接口的BeanFactoryPostProcessor類調用其接口方法postProcessBeanFactory
    • 否,直接調用BeanFactoryPostProcessor類的接口方法postProcessBeanFactory
  2. 查詢全部BeanFactory中註冊的BeanDefinition有類型爲BeanFactoryPostProcessor的beanName,再根據是否實現PriorityOrdered或Ordered接口進行排序,調用接口方法postProcessBeanFactory,先執行PriorityOrdered接口的,其次爲Ordered,最後執行其餘的。

    public static void invokeBeanFactoryPostProcessors(
     	ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
    
     // Invoke BeanDefinitionRegistryPostProcessors first, if any.
     Set<String> processedBeans = new HashSet<String>();
    
     // 判斷beanFactory是否爲BeanDefinitionRegistry的子類
     if (beanFactory instanceof BeanDefinitionRegistry) {
     	BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
     	List<BeanFactoryPostProcessor> regularPostProcessors = new LinkedList<BeanFactoryPostProcessor>();
     	List<BeanDefinitionRegistryPostProcessor> registryPostProcessors =
     			new LinkedList<BeanDefinitionRegistryPostProcessor>();
    
     	// 遍歷內置beanFactoryPostProcessors,查詢BeanFactoryPostProcessor的子接口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);
     		}
     	}
     	OrderComparator.sort(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);
     		}
     	}
     	OrderComparator.sort(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.
     OrderComparator.sort(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));
     }
     OrderComparator.sort(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);

    }

註冊BeanPostProcessor

refresh方法中的registerBeanPostProcessors,用來註冊BeanPostProcessor到BeanFactory中,具體實現也是經過PostProcessorRegistrationDelegate委託類來進行。

protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
	PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}

處理的過程相似於上面的BeanFactoryPostProcessor,都是從BeanFactory中查詢類型爲BeanPostProcessor的beanName,再根據其是否實現PriorityOrdered,Ordered接口排序,而後統一調用BeanFactory的addBeanPostProcessor方法註冊。

最後硬編碼方式內置增長了一個監聽器發現的BeanPostProcessor的實現ApplicationListenerDetector,用來在bean初始化以後,判斷bean是否實現ApplicationListener接口,若是是,就將其註冊到applicationListeners中。

bean的預實例化

若是bean配置的是非懶加載的單例(默認爲懶加載),則在容器啓動過程當中就經過getBean方法對其實例化,這個操做在refresh方法中對應finishBeanFactoryInitialization子方法。

protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
	// Initialize conversion service for this context.
	// 初始化類型轉換服務bean
	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));
	}

	// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
	String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
	for (String weaverAwareName : weaverAwareNames) {
		getBean(weaverAwareName);
	}

	// Stop using the temporary ClassLoader for type matching.
	// 中止使用臨時類加載器
	beanFactory.setTempClassLoader(null);

	// Allow for caching all bean definition metadata, not expecting further changes.
	// 凍結bean definition元數據配置
	beanFactory.freezeConfiguration();

	// Instantiate all remaining (non-lazy-init) singletons.
	// 實例化non-lazy-init單例
	beanFactory.preInstantiateSingletons();
}

在預實例化時,對FactoryBean也作了特殊的處理,只有SmartFactoryBean的子類而且isEagerInit方法爲true時,纔會執行FactoryBean的getObject方法建立真正的對象。而且建立的對象是SmartInitializingSingleton的子類時,執行接口方法afterSingletonsInstantiated。

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.
	List<String> beanNames = new ArrayList<String>(this.beanDefinitionNames);

	// Trigger initialization of all non-lazy singleton beans...
	for (String beanName : beanNames) {
		RootBeanDefinition bd = getMergedLocalBeanDefinition(beanName);
		if (!bd.isAbstract() && bd.isSingleton() && !bd.isLazyInit()) {
			if (isFactoryBean(beanName)) {
				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](https://my.oschina.net/u/1162528)
						public Boolean run() {
							return ((SmartFactoryBean<?>) factory).isEagerInit();
						}
					}, getAccessControlContext());
				}
				else {
					isEagerInit = (factory instanceof SmartFactoryBean &&
							((SmartFactoryBean<?>) factory).isEagerInit());
				}
				if (isEagerInit) {
					getBean(beanName);
				}
			}
			else {
				getBean(beanName);
			}
		}
	}

	// Trigger post-initialization callback for all applicable beans...
	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](https://my.oschina.net/u/1162528)
					public Object run() {
						smartSingleton.afterSingletonsInstantiated();
						return null;
					}
				}, getAccessControlContext());
			}
			else {
				smartSingleton.afterSingletonsInstantiated();
			}
		}
	}
}

發佈容器刷新完成事件

finishRefresh方法中對生命週期處理類進行初始化並刷新,而後發佈了容器刷新完成事件。到此容器刷新的過程就結束了。

protected void finishRefresh() {
	// Initialize lifecycle processor for this context.
	initLifecycleProcessor();

	// Propagate refresh to lifecycle processor first.
	getLifecycleProcessor().onRefresh();

	// Publish the final event.
	publishEvent(new ContextRefreshedEvent(this));

	// Participate in LiveBeansView MBean, if active.
	LiveBeansView.registerApplicationContext(this);
}

##異常##

固然若是過程當中拋出了BeansException異常,則須要對Spring容器進行清理。

// Destroy already created singletons to avoid dangling resources.
// 銷燬全部實例化的單例bean
destroyBeans();

// Reset 'active' flag.
// 重置active爲false
cancelRefresh(ex);
相關文章
相關標籤/搜索