本文是針對Srping的ClassPathXMLApplicationContext來進行源碼解析,在本篇博客中將不會講述spring Xml解析注冊代碼,因為ApplicationContext是BeanFactory的擴展版本,ApplicationContext的GetBean和xml解析注冊BeanDefinition都是用一套代碼,如果您是第一次看請先看一下XMLBeanFactory解析和BeanFactory.GetBean源碼解析:
- XMLBeanFactory源碼解析地址:https://www.cnblogs.com/technology-blog/p/14543685.html
- BeanFactory.getBean源碼解析地址:https://www.cnblogs.com/technology-blog/p/14543902.html
作者整理了spring-framework 5.x的源碼注釋,代碼已經上傳者作者的GitHub了,可以讓讀者更好的理解,地址:
- 接下來直接上源碼:
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源碼解析;
- 接下來我們看一下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方法;
- 源碼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方法幾乎涵蓋了所有的基礎和擴展功能,接下來看一下這個方法都做了什么;
- 刷新上下文,初始化前的准備工作;
- 加載beanFactory,經過這個方法 applicationContext就有了BeanFactory的所有功能
- 對beanFactory進行各種功能填充
- 允許在這里對BeanFactory的二次加工,例如:可以在這里進行硬編碼方法的對BeanFactory進行BeanFactoryPostProcessor或BeanPostProcessor的操作;在這里簡單說一下BeanFactoryPostProcessor是在bean實例化之前執行的,BeanPostProcessor是在初始化方法前后執行的,BeanFactoryPostProcessor操作的是BeanFactoryBeanPostProcessor操作的是Bean,其次這里還涉及了一個擴展BeanDefinitionRegistryPostProcessor它是繼承了BeanFactoryPostProcessor,並且還有自己的定義方法 postProcessBeanDefinitionRegistry,這個方法可以操作BeanDefinitionRegistry,BeanDefinitionRegistry有個最主要的方法就是registerBeanDefinition,可以注冊BeanDefinition,可以用這方法來處理一下不受spring管理的一下bean;
- 處理所有的BeanFactoryPostProcessor,也可以說是激活BeanFactory處理器,在這個方法里會先處理BeanDefinitionRegistryPostProcessor,在處理BeanFactoryPostProcessor,因為BeanDefinitionRegistryPostProcessor有自己的定義,所以先執行;
- 注冊BeanPostProcessors ,這里只是注冊,真正地調用在getBean的時候 BeanPostProcessors是在init方法前后執行 BeanPostProcessor執行位置:doCreateBean --> initializeBean --> applyBeanPostProcessorsBeforeInitialization 和 applyBeanPostProcessorsAfterInitialization方法中;
- 為上下文初始化Message源,(比如國際化處理) 這里沒有過多深入;
- 初始化應用消息廣播,初始化 applicationEventMulticaster ,判斷使用自定義的還是默認的;
- 留給子類來初始化其它的bean;
- 在所有注冊的bean中查找 ApplicationListener bean,注冊到消息廣播器中;
- 初始化剩下的單實例(非懶加載),這里會是涉及conversionService,LoadTimeWeaverAware,凍結BeanFactory,初始化Bean等操作;
- 完成刷新過程,包括 清除 下文級資源(例如掃描的元數據),通知生命周期處理器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()方法;
- initPropertySources證符合Spring的開放式結構設計,給用戶最大擴展Spring的能力。用戶可以根據自身的需要重寫initPropertySourece方法,並在方法中進行個性化的屬性處理及設置。
- 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:
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);
}
}
看一下上述方法都做了什么:
判斷BeanFactory是否存在,如果存在則銷毀所有Bean,然后關閉BeanFactory;
使用createBeanFactory方法直接新建一個DefaultListableBeanFactory,內部使用的是DefaultListableBeanFactory實例;
設置BeanFactory的設置序列化id
定制beanFactory工廠,也就是給allowBeanDefinitionOverriding(是否允許覆蓋同名稱的Bean)和allowCircularReferences(是否允許bean存在循環依賴),可通過setAllowBeanDefinitionOverriding和setAllowCircularReferences賦值,這里就可通過商編初始化方法中的initPropertySources方法來進行賦值;
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); } }
- 加載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());
}
}
不說廢話,直接看這個方法都做了什么:
設置BeanFactory的classLoader為當前context的classloader;
設置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>
- 為BeanFactory增加一個默認的 PropertyEditor 這個主要對bean的屬性等設置管理的一個工具 增加屬性注冊編輯器 例如:User類中 startDate 類型 date 但是xml property的value是2019-10-10,在啟動的時候就會報錯,類型轉換不成功,這里可以使用繼承PropertyEditorSupport這個類機型重寫並注入即可使用;beanFactory會在初始化BeanWrapper (initBeanWrapper)中調用 ResourceEditorRegistrar 的 registerCustomEditors 方法進行初始化;
配置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,這里相信大家都用過,就不多說了;
設置幾個忽略自動裝配的接口 在addBeanPostProcessor方法中已經對下面幾個類做了處理,他們就不是普通的bean了,所以在這里spring做bean的依賴的時候忽略,在doCreateBean 方法中的 populateBean 方法中的 autowireByName 或 autowireByType 中的 unsatisfiedNonSimpleProperties 中的 !isExcludedFromDependencyCheck(pd) 判斷,如果存在則不做依賴注入了;
設置幾個注冊依賴 參考spring源碼深度解析原文:當注冊依賴解析后,例如當注冊了對BeanFactory的解析依賴后,當bean的屬性注入的時候,一旦檢測到屬性為BeanFactory的類型便會將beanFactory 實例注入進去;
添加BeanPostProcessor,這里是添加ApplicationListener,是寄存器早期處理器;這里可以看作者的源碼測試,在spring-context的test測試類下有;
增加了對AxpectJ的支持
注冊默認的系統環境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();
}
上述代碼看起來很多,但是總計起來就三件事:
- 執行硬編碼的和主動注入的BeanDefinitionRegistryPostProcessor,調用postProcessBeanDefinitionRegistry方法;
- 執行硬編碼的和主動注入的BeanFactoryPostProcessor,調用postProcessBeanFactory方法;
- 自動注入的可繼承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差不多:
- 使用priorityOrdered,Ordered或無序保證順序;
- 通過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方法做了三件事情:
- 添加 ApplicationListener 這里通過硬編碼 addApplicationListener 方法添加的;
- 添加 ApplicationListener 是通過自動注冊添加的
- 發布早起事件
- 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方法做了五件事情:
- 設置BeanFactory的conversionService,conversionService用於類型轉換使用, 例如:User類中 startDate 類型 date 但是xml property的value是2019-10-10,在啟動的時候就會報錯,類型轉換不成功,可以使用conversionService;書中170頁有具體代碼;
- 添加BeanFactory的addEmbeddedValueResolver,讀取配置信息放到這里,可以通過EmbeddedValueResolverAware來獲取,參考:https://www.cnblogs.com/winkey4986/p/7001173.html
- 得到所有的實現了LoadTimeWeaverAware接口的子類名稱,初始化它們,用來加載Spring Bean時織入第三方模塊,如AspectJ,我們在后面詳細講解。
- 停止使用臨時類加載器 就是在這里不讓使用呢 ClassLoader 了
- 凍結所有bean定義,說明你注冊的bean將不被修改或進行任何進一步的處理 就是不讓改了 BeanDefinition
- 初始化所有非懶加載的 單例 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初始化的最后一個方法了,他做了一些結尾的事情:
- 清除 下文級資源(例如掃描的元數據)。
- 在當前context中初始化 lifecycle,lifecycle 有自己的 start/ stop方法,實現此接口后spring保證在啟動的時候調用start方法開始生命周期 關閉的時候調用 stop方法結束生命周期。
- onRefresh 啟動所有實現了 lifecycle 的方法,調用了start方法。
- 當ApplicationContext初始化完成發布事件 處理后續事宜。
- LiveBeansView.registerApplicationContext(this)這個代碼沒有太明白,有大神可以留言;
至此ApplicationContext的源碼就都已經分析完成了,其中有很多地方很難懂,大家可以對應着源碼一起看,會好理解一些,如果其中有錯誤,歡迎大神指點,在下方留言。