前面的章節(jié)介紹了SpringIoC的基礎(chǔ)容器BeanFactory螺捐,接下來的章節(jié)分析Spring的高級容器ApplicationContext绳慎。關(guān)于兩者的介紹题涨,可以參考以前的章節(jié)。接下來我們以ClassPathXmlApplicationContext為例分析ApplicationContext的創(chuàng)建過程。
引、ApplicationContext創(chuàng)建過程簡析
/**
* 創(chuàng)建一個新的ClassPathXmlApplicationContext容器
* 從指定的xml文件加載BeanDefinition并自動刷新容器
* @param configLocation 配置文件位置
* @throws BeansException 容器創(chuàng)建失敗,拋出BeansException異常
*/
public ClassPathXmlApplicationContext(String configLocation) throws BeansException {
this(new String[] {configLocation}, true, null);
}
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, @Nullable ApplicationContext parent) throws BeansException {
// 調(diào)用父類構(gòu)造器
super(parent);
// 設(shè)定配置文件路徑
setConfigLocations(configLocations);
if (refresh) {
// 擴展功能
refresh();
}
}
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// 1棚菊、準備刷新上下文環(huán)境
prepareRefresh();
// 2、讀取xml并初始化BeanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// 3叔汁、填充BeanFactory功能
prepareBeanFactory(beanFactory);
try {
// 4统求、子類覆蓋方法額外處理(空方法)
postProcessBeanFactory(beanFactory);
// 5检碗、調(diào)動BeanFactoryPostProcessor
invokeBeanFactoryPostProcessors(beanFactory);
// 6、注冊BeanPostProcessors
registerBeanPostProcessors(beanFactory);
// 7码邻、初始化Message資源
initMessageSource();
// 8折剃、初始事件廣播器
initApplicationEventMulticaster();
// 9、留給子類初始化其他Bean(空的模板方法)
onRefresh();
// 10像屋、注冊事件監(jiān)聽器
registerListeners();
// 11怕犁、初始化其他的單例Bean(非延遲加載的)
finishBeanFactoryInitialization(beanFactory);
// 12、完成刷新過程,通知生命周期處理器lifecycleProcessor刷新過程,同時發(fā)出ContextRefreshEvent通知
finishRefresh();
}
catch (BeansException ex) {
// 13己莺、銷毀已經(jīng)創(chuàng)建的Bean
destroyBeans();
// 14奏甫、重置容器激活標簽
cancelRefresh(ex);
throw ex;
}
finally {
resetCommonCaches();
}
}
}
逐步分析refresh()方法。
1凌受、prepareRefresh刷新上下文的準備工作
/**
* 準備刷新上下文環(huán)境阵子,設(shè)置它的啟動日期和活動標志,以及執(zhí)行任何屬性源的初始化胜蛉。
* Prepare this context for refreshing, setting its startup date and
* active flag as well as performing any initialization of property sources.
*/
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
// 在上下文環(huán)境中初始化任何占位符屬性源挠进。(空的方法,留給子類覆蓋)
initPropertySources();
// 驗證需要的屬性文件是否都已放入環(huán)境中
getEnvironment().validateRequiredProperties();
// 允許收集早期的應(yīng)用程序事件,一旦有了多播器腾么,就可以發(fā)布……
this.earlyApplicationEvents = new LinkedHashSet<>();
}
2、obtainFreshBeanFactory->讀取xml并初始化BeanFactory
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 刷新BeanFactory并返回BeanFactory對象
refreshBeanFactory();
return getBeanFactory();
}
protected final void refreshBeanFactory() throws BeansException {
// 1杈湾、如果BeanFactory的實例已經(jīng)存在,則銷毀并關(guān)閉
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
// 2解虱、重新創(chuàng)建BeanFactory
try {
// 創(chuàng)建BeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 為BeanFactory設(shè)置id
beanFactory.setSerializationId(getId());
// 定制beanFactory
customizeBeanFactory(beanFactory);
// 加載BeanDefinition
loadBeanDefinitions(beanFactory);
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
該方法的主要作用就是保證獲取一個全新的beanFactory,關(guān)于beanFactory我們在前面已經(jīng)做了很多介紹了漆撞,這里不在說明殴泰。
3、prepareBeanFactory-->填充BeanFactory功能
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// Tell the internal bean factory to use the context's class loader etc.
// 設(shè)置beanFactory的classLoader
beanFactory.setBeanClassLoader(getClassLoader());
// 設(shè)置beanFactory的表達式語言處理器,Spring3開始增加了對語言表達式的支持,默認可以使用#{bean.xxx}的形式來調(diào)用相關(guān)屬性值
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 為beanFactory增加一個默認的propertyEditor,這個主要是對bean的屬性等設(shè)置管理的一個工具
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
// 添加ApplicationContextAwareProcessor
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
// 設(shè)置忽略自動裝配的接口
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.
// 設(shè)置幾個自動裝配的特殊規(guī)則
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.
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.
// 注冊默認的系統(tǒng)環(huán)境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());
}
}
4浮驳、postProcessBeanFactory
該方法是個空的模板方法悍汛。
5、invokeBeanFactoryPostProcessors-->調(diào)用BeanFactoryPostProcessor
BeanFactoryPostProcessor在Spring中非常重要至会,詳細分析其調(diào)用過程离咐。
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
//getBeanFactoryPostProcessors->獲取注冊的BeanFactoryPostProcessor
PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
// Detect a LoadTimeWeaver and prepare for weaving, if found in the meantime
// (e.g. through an @Bean method registered by ConfigurationClassPostProcessor)
if (beanFactory.getTempClassLoader() == null && beanFactory.containsBean(LOAD_TIME_WEAVER_BEAN_NAME)) {
beanFactory.addBeanPostProcessor(new LoadTimeWeaverAwareProcessor(beanFactory));
beanFactory.setTempClassLoader(new ContextTypeMatchClassLoader(beanFactory.getBeanClassLoader()));
}
}
通過PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors(beanFactory, getBeanFactoryPostProcessors());
獲取注冊的BeanFactoryPostProcessor并調(diào)用。
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 1奉件、首先調(diào)用BeanDefinitionRegistryPostProcessors
Set<String> processedBeans = new HashSet<>();
// beanFactory是BeanDefinitionRegistry類型
if (beanFactory instanceof BeanDefinitionRegistry) {
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 定義BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// 定義BeanDefinitionRegistryPostProcessor集合
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 循環(huán)手動注冊的beanFactoryPostProcessors
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 如果是BeanDefinitionRegistryPostProcessor的實例話,則調(diào)用其postProcessBeanDefinitionRegistry方法,對bean進行注冊操作
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
// 如果是BeanDefinitionRegistryPostProcessor類型,則直接調(diào)用其postProcessBeanDefinitionRegistry
BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
// 否則則將其當做普通的BeanFactoryPostProcessor處理,直接加入regularPostProcessors集合,以備后續(xù)處理
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.
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 首先調(diào)用實現(xiàn)了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集合
registryProcessors.addAll(currentRegistryProcessors);
// 調(diào)用所有實現(xiàn)了PriorityOrdered的的BeanDefinitionRegistryPostProcessors的postProcessBeanDefinitionRegistry方法,注冊bean
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空currentRegistryProcessors,以備下次使用
currentRegistryProcessors.clear();
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
// 其次,調(diào)用實現(xiàn)了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集合
registryProcessors.addAll(currentRegistryProcessors);
// 調(diào)用所有實現(xiàn)了PriorityOrdered的的BeanDefinitionRegistryPostProcessors的postProcessBeanDefinitionRegistry方法,注冊bean
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空currentRegistryProcessors,以備下次使用
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
// 最后,調(diào)用其他的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集合
registryProcessors.addAll(currentRegistryProcessors);
// 調(diào)用其他的BeanDefinitionRegistryPostProcessors的postProcessBeanDefinitionRegistry方法,注冊bean
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空currentRegistryProcessors,以備下次使用
currentRegistryProcessors.clear();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
// 調(diào)用所有BeanDefinitionRegistryPostProcessor(包括手動注冊和通過配置文件注冊)
// 和BeanFactoryPostProcessor(只有手動注冊)的回調(diào)函數(shù)-->postProcessBeanFactory
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
// 2宵蛀、如果不是BeanDefinitionRegistry的實例,那么直接調(diào)用其回調(diào)函數(shù)即可-->postProcessBeanFactory
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!
// 3、上面的代碼已經(jīng)處理完了所有的BeanDefinitionRegistryPostProcessors和手動注冊的BeanFactoryPostProcessor
// 接下來要處理通過配置文件注冊的BeanFactoryPostProcessor
// 首先獲取所有的BeanFactoryPostProcessor(注意:這里獲取的集合會包含BeanDefinitionRegistryPostProcessors)
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered, Ordered, and the rest.
// 這里,將實現(xiàn)了PriorityOrdered,Ordered的處理器和其他的處理器區(qū)分開來,分別進行處理
// PriorityOrdered有序處理器
List<BeanFactoryPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// Ordered有序處理器
List<String> orderedPostProcessorNames = new ArrayList<>();
// 無序處理器
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
for (String ppName : postProcessorNames) {
// 判斷processedBeans是否包含當前處理器(processedBeans中的處理器已經(jīng)被處理過);如果包含,則不做任何處理
if (processedBeans.contains(ppName)) {
// skip - already processed in first phase above
}
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 加入到PriorityOrdered有序處理器集合
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
// 加入到Ordered有序處理器集合
orderedPostProcessorNames.add(ppName);
}
else {
// 加入到無序處理器集合
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
// 首先調(diào)用實現(xiàn)了PriorityOrdered接口的處理器
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
// 其次,調(diào)用實現(xiàn)了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.
// 最后,調(diào)用無序處理器
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...
// 清理元數(shù)據(jù)
beanFactory.clearMetadataCache();
}
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.
// 注冊一個BeanPostProcessorChecker,它是BeanPostProcessor的子類
// 用于在BeanPostProcessor實例化期間創(chuàng)建bean時記錄信息消息县貌,即當bean不符合由所有BeanPostProcessors處理的資格時术陶。
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered, Ordered, and the rest.
// 對實現(xiàn)了PriorityOrdered接口,Ordered接口,內(nèi)部BeanPostProcessor和其他的BeanPostProcessor分類處理
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
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.
// 首先注冊實現(xiàn)了PriorityOrdered(有限排序接口)BeanPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 其次,注冊實現(xiàn)了Ordered(排序接口的)BeanPostProcessor
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.
// 然后,注冊無序的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.
// 最后,注冊內(nèi)部BeanPostProcessors
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).
// 注冊一個ApplicationListenerDetector用來偵測ApplicationListener類型的bean
// 并將它們加入到容器的applicationEventMulticaster或applicationListeners集合中
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
6、注冊BeanPostProcessors
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
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.
// 1煤痕、注冊一個BeanPostProcessorChecker,它是BeanPostProcessor的子類
// 用于在BeanPostProcessor實例化期間創(chuàng)建bean時記錄信息消息梧宫,即當bean不符合由所有BeanPostProcessors處理的資格時接谨。
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// Separate between BeanPostProcessors that implement PriorityOrdered, Ordered, and the rest.
// 2、對實現(xiàn)了PriorityOrdered接口,Ordered接口,內(nèi)部BeanPostProcessor和其他的BeanPostProcessor分類處理
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
List<String> orderedPostProcessorNames = new ArrayList<>();
List<String> nonOrderedPostProcessorNames = new ArrayList<>();
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);
}
}
// 3塘匣、注冊BeanPostProcessors
// First, register the BeanPostProcessors that implement PriorityOrdered.
// 首先注冊實現(xiàn)了PriorityOrdered(有限排序接口)BeanPostProcessor
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
// 其次,注冊實現(xiàn)了Ordered(排序接口的)BeanPostProcessor
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.
// 然后,注冊無序的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.
// 最后,注冊內(nèi)部BeanPostProcessors
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).
// 注冊一個ApplicationListenerDetector用來偵測ApplicationListener類型的bean
// 并將它們加入到容器的applicationEventMulticaster或applicationListeners集合中
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
7脓豪、初始化Message資源
該方法不是很重要,留在以后分析吧馆铁。跑揉。。
8埠巨、初始事件廣播器
protected void initApplicationEventMulticaster() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
// 1历谍、默認使用內(nèi)置的事件廣播器,如果有的話.
// 我們可以在配置文件中配置Spring事件廣播器或者自定義事件廣播器
// 例如: <bean id="applicationEventMulticaster" class="org.springframework.context.event.SimpleApplicationEventMulticaster"></bean>
if (beanFactory.containsLocalBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME)) {
this.applicationEventMulticaster = beanFactory.getBean(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, ApplicationEventMulticaster.class);
}
// 2、否則,新建一個事件廣播器,SimpleApplicationEventMulticaster是spring的默認事件廣播器
else {
this.applicationEventMulticaster = new SimpleApplicationEventMulticaster(beanFactory);
beanFactory.registerSingleton(APPLICATION_EVENT_MULTICASTER_BEAN_NAME, this.applicationEventMulticaster);
}
}
9辣垒、onRefresh-->留給子類初始化其他Bean
該方法是個空的模板方法
10望侈、注冊事件監(jiān)聽器
protected void registerListeners() {
// Register statically specified listeners first.
// 首先,注冊指定的靜態(tài)事件監(jiān)聽器,在spring boot中有應(yīng)用
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!
// 其次,注冊普通的事件監(jiān)聽器
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...
// 如果有早期事件的話,在這里進行事件廣播
// 因為前期SimpleApplicationEventMulticaster尚未注冊,無法發(fā)布事件勋桶,
// 因此早期的事件會先存放在earlyApplicationEvents集合中脱衙,這里把它們?nèi)〕鰜磉M行發(fā)布
// 所以早期事件的發(fā)布時間節(jié)點是早于其他事件的
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
// 早期事件廣播器是一個Set<ApplicationEvent>集合,保存了無法發(fā)布的早期事件,當SimpleApplicationEventMulticaster
// 創(chuàng)建完之后隨即進行發(fā)布,同事也要將其保存的事件釋放
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
11、初始化其他的單例Bean(非延遲加載的)
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// Initialize conversion service for this context.
// 判斷有無ConversionService(bean屬性類型轉(zhuǎn)換服務(wù)接口),并初始化
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.
// 如果beanFactory中不包含EmbeddedValueResolver,則向其中添加一個EmbeddedValueResolver
// EmbeddedValueResolver-->解析bean中的占位符和表達式
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// Initialize LoadTimeWeaverAware beans early to allow for registering their transformers early.
// 初始化LoadTimeWeaverAware類型的bean
// LoadTimeWeaverAware-->加載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.
// 釋放臨時類加載器
beanFactory.setTempClassLoader(null);
// Allow for caching all bean definition metadata, not expecting further changes.
// 凍結(jié)緩存的BeanDefinition元數(shù)據(jù)
beanFactory.freezeConfiguration();
// Instantiate all remaining (non-lazy-init) singletons.
// 初始化其他的非延遲加載的單例bean
beanFactory.preInstantiateSingletons();
}
12例驹、完成刷新過程,通知生命周期處理器lifecycleProcessor刷新過程,同時發(fā)出ContextRefreshEvent通知
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.
// 調(diào)用生命周期處理器的onRefresh方法
getLifecycleProcessor().onRefresh();
// Publish the final event.
// 推送容器刷新事件
publishEvent(new ContextRefreshedEvent(this));
// Participate in LiveBeansView MBean, if active.
// MBean...沒弄明白
LiveBeansView.registerApplicationContext(this);
}