-- 以下內容均基於2.1.8.RELEASE版本
緊接着上一篇(四)SpringBoot啟動過程的分析-預處理ApplicationContext, 本文將分析上下文容器准備完成之后開始執行刷新流程
// SpringApplication.java
private void refreshContext(ConfigurableApplicationContext context) {
refresh(context);
if (this.registerShutdownHook) {
try {
context.registerShutdownHook();
}
catch (AccessControlException ex) {
// Not allowed in some environments.
}
}
}
// 真正的refresh方法在AbstractApplicationContext類中
protected void refresh(ApplicationContext applicationContext) {
Assert.isInstanceOf(AbstractApplicationContext.class, applicationContext);
((AbstractApplicationContext) applicationContext).refresh();
}
// AbstractApplicationContext.java
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
initMessageSource();
// Initialize event multicaster for this context.
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
onRefresh();
// Check for listener beans and register them.
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
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();
}
}
}
在refresh方法中清晰的划分了刷新容器的步驟。
prepareRefresh()
主要用於清除元數據Reader的緩存,設置應用程序啟動的時間,設置應用程序的活動標記,初始化屬性源。
// AnnotationConfigServletWebServerApplicationContext.java
protected void prepareRefresh() {
this.scanner.clearCache();
super.prepareRefresh();
}
// AbstractApplicationContext.java
protected void prepareRefresh() {
// 設置開始執行的時間和活動標記
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());
}
}
// ①
initPropertySources();
// ②
// Validate that all properties marked as required are resolvable:
// see 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<>();
}
① - 初始化屬性資源
// StandardServletEnvironment.java
public void initPropertySources(@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {
WebApplicationContextUtils.initServletPropertySources(getPropertySources(), servletContext, servletConfig);
}
// WebApplicationContextUtils.java
public static void initServletPropertySources(MutablePropertySources sources,
@Nullable ServletContext servletContext, @Nullable ServletConfig servletConfig) {
Assert.notNull(sources, "'propertySources' must not be null");
String name = StandardServletEnvironment.SERVLET_CONTEXT_PROPERTY_SOURCE_NAME;
// servletContext不為空且有相關配置的情況
if (servletContext != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) {
sources.replace(name, new ServletContextPropertySource(name, servletContext));
}
// servletConfig不為空且有相關配置的情況
name = StandardServletEnvironment.SERVLET_CONFIG_PROPERTY_SOURCE_NAME;
if (servletConfig != null && sources.contains(name) && sources.get(name) instanceof StubPropertySource) {
sources.replace(name, new ServletConfigPropertySource(name, servletConfig));
}
}
在內部調用了WebApplicationContextUtils.initServletPropertySources方法,由名稱可得知,它用於初始化Servlet的屬性資源,在實際執行過程中分別根據ServletContext和ServletConfig的值來判定是否要將指定的配置包裝為ServletContextPropertySource、ServletConfigPropertySource在實際調試過程中他們的值都為空,也就是沒有進行任何操作。
② - 檢查必備屬性,此處是用於檢查哪些屬性是必不可少的,例如可以設置"example.address"這個屬性必須不為空。
③ - 重新對監聽器排序
prepareBeanFactory(beanFactory)
// AbstractApplicationContext.java
protected void prepareBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 設置類加載器
// Tell the internal bean factory to use the context's class loader etc.
beanFactory.setBeanClassLoader(getClassLoader());
// 設置SpringEL表達式解析器
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
// 設置屬性編輯器注冊
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// ① 忽略指定的接口注入
// Configure the bean factory with context callbacks.
beanFactory.addBeanPostProcessor(new ApplicationContextAwareProcessor(this));
beanFactory.ignoreDependencyInterface(EnvironmentAware.class);
beanFactory.ignoreDependencyInterface(EmbeddedValueResolverAware.class);
beanFactory.ignoreDependencyInterface(ResourceLoaderAware.class);
beanFactory.ignoreDependencyInterface(ApplicationEventPublisherAware.class);
beanFactory.ignoreDependencyInterface(MessageSourceAware.class);
beanFactory.ignoreDependencyInterface(ApplicationContextAware.class);
// 指定對特定接口注入時實際的注入對象,例如有某對象想要注入BeanFactory,則實際將會指定它注入的是當前設置的BeanFactory
// 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);
// 添加和移除ApplicationListener
// Register early post-processor for detecting inner beans as ApplicationListeners.
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(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()));
}
// 注冊默認環境對象
// 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());
}
}
① - 這里的忽略依賴接口,是指這些Aware接口的實現類在Spring中將會自動忽略接口實現類中和setter方法入參相同的類型,舉例說明
public interface EnvironmentAware extends Aware {
void setEnvironment(Environment environment);
}
public class MyEnvironmentAware implements Environment {
private Environment environment;
@Overwired
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
示例中展示了如何使用EnvironmentAware接口來實現在自定義代碼中獲取Environment,上面所說的忽略,是指在Spring自動裝配MyEnvironment這個類的時候,會自動忽略到setEnvironment方法中的Environment對象注入。在忽略接口的第一行代碼添加了一個ApplicationContextAwareProcessor,而它則是Spring框架統一來設置這些Aware接口實現類的處理器。
postProcessBeanFactory(beanFactory)
在當前AbstractApplicationContext類中的postProcessBeanFactory方法並未實現,由其子類實現。
// AnnotationConfigServletWebServerApplicationContext.java
// 實現一
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// ①
super.postProcessBeanFactory(beanFactory);
// ②
if (this.basePackages != null && this.basePackages.length > 0) {
this.scanner.scan(this.basePackages);
}
// ③
if (!this.annotatedClasses.isEmpty()) {
this.reader.register(ClassUtils.toClassArray(this.annotatedClasses));
}
}
① - 調用父類的實現
// ServletWebServerApplicationContext.java
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
// 添加用於處理WebApplicationContextServletContextAware接口的processor
beanFactory.addBeanPostProcessor(new WebApplicationContextServletContextAwareProcessor(this));
// 忽略ServletContextAware接口的注入
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
registerWebApplicationScopes();
}
// 注冊web應用的作用域
public static void registerWebApplicationScopes(ConfigurableListableBeanFactory beanFactory,
@Nullable ServletContext sc) {
beanFactory.registerScope(WebApplicationContext.SCOPE_REQUEST, new RequestScope());
beanFactory.registerScope(WebApplicationContext.SCOPE_SESSION, new SessionScope());
if (sc != null) {
ServletContextScope appScope = new ServletContextScope(sc);
beanFactory.registerScope(WebApplicationContext.SCOPE_APPLICATION, appScope);
// Register as ServletContext attribute, for ContextCleanupListener to detect it.
sc.setAttribute(ServletContextScope.class.getName(), appScope);
}
beanFactory.registerResolvableDependency(ServletRequest.class, new RequestObjectFactory());
beanFactory.registerResolvableDependency(ServletResponse.class, new ResponseObjectFactory());
beanFactory.registerResolvableDependency(HttpSession.class, new SessionObjectFactory());
beanFactory.registerResolvableDependency(WebRequest.class, new WebRequestObjectFactory());
if (jsfPresent) {
FacesDependencyRegistrar.registerFacesDependencies(beanFactory);
}
}
② - 根據basePackage指定的位置進行掃描bean
③ - 根據注解來掃描指定的bean
invokeBeanFactoryPostProcessors()
主要用於調用BeanFactoryPostProcessors的實現
protected void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 調用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()));
}
}
在調用BeanFactoryPostProcessor時,會首先調用BeanDefinitionRegistryPostProcessor, 因為后者是對前者的擴展,並且有可能在后者中又重新注冊了前者的其他實例。由於PostProcessorRegistrationDelegate.invokeBeanFactoryPostProcessors()方法過長,這里直接寫行內注釋能夠比較直觀的分析前后關系。
public static void invokeBeanFactoryPostProcessors(ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
// 已處理的Bean
Set<String> processedBeans = new HashSet<>();
// 判斷當前的BeanFactory是否為一個Bean注冊器,實際上就是代表同時實現了BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor接口的實現
// 對於同時實現兩個接口的類,將先調用BeanDefinitionRegistryPostProcessor里面的方法,再調用BeanFactoryPostProcessor里面的方法
// 在調用的時候又要區分是實現了PriorityOrdered還是Ordered接口。
if (beanFactory instanceof BeanDefinitionRegistry) {
// 轉換為注冊器
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
// 用於存放常規的BeanFactoryPostProcessor
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
// 用於存放BeanFactoryPostProcessor的擴展BeanDefinitionRegistryPostProcessor,這里是一個匯總的列表
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
// 遍歷傳入的BeanFactoryPostProcessor
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
// 優先執行BeanFactoryPostProcessor的擴展類BeanDefinitionRegistryPostProcessor,它的優先級最高
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
// 類型轉換
BeanDefinitionRegistryPostProcessor registryProcessor = (BeanDefinitionRegistryPostProcessor) postProcessor;
// 調用postProcessBeanDefinitionRegistry()方法,內部可能注冊了Bean,也可能重新定義了一些普通的BeanFactoryPostProcessor
registryProcessor.postProcessBeanDefinitionRegistry(registry);
// 添加到已處理列表
registryProcessors.add(registryProcessor);
}
else {
// 對比上面if代碼塊會發現,這里沒有作調用,直接先保存在常規列表內部,因為常規的Processor在調用的時候還有其他考慮,接着往下看便是
regularPostProcessors.add(postProcessor);
}
}
// 不要在這里初始化FactoryBean(請看清是FactoryBean,工廠類,不是類工廠(BeanFactory),他們有巨大的差異),需要保留所有的常規類未初始化,以便使用BeanFactoryPostProcessor對其處理
// Do not initialize FactoryBeans here: We need to leave all regular beans
// uninitialized to let the bean factory post-processors apply to them!
// 根據BeanDefinitionRegistryPostProcessors 實現的接口划分為三類:實現了PriorityOrdered的、實現了Ordered的以及前面兩者都沒實現的
// Separate between BeanDefinitionRegistryPostProcessors that implement
// PriorityOrdered, Ordered, and the rest.
// 保存當前將要處理的BeanDefinitionRegistryPostProcessor列表,每處理完一種分類的就清空
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// 首先調用實現了PriorityOrdered接口的BeanDefinitionRegistryPostProcessors
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
// 獲取當前Bean工廠內部所有的,類型為BeanDefinitionRegistryPostProcessor.class的后處理器名稱
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
// 篩選出實現了PriorityOrdered接口的后處理器,放入當前處理列表
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
// 同時放入已處理列表
processedBeans.add(ppName);
}
}
// 按照優先級排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
// 添加實現了PriorityOrder接口的BeanDefinitionRegistryPostProcessor到它的匯總列表里面
registryProcessors.addAll(currentRegistryProcessors);
// 調用所有的BeanDefinitionRegistryPostProcessor實例的postProcessBeanDefinitionRegistry()方法
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清除內部的實現了PriorityOrder的BeanDefinitionRegistryPostProcessor
currentRegistryProcessors.clear();
// 上面是處理實現了PriorityOrdered接口的,這里處理實現了Ordered接口的, 為何這里又獲取了一次postProcessorNames,前面不是才獲取么?
// 這里獲取一次是因為前面處理的時候有可能又加入了新的BeanDefinitionRegistryPostProcessor
// Next, invoke the BeanDefinitionRegistryPostProcessors that implement Ordered.
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);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
// 清空上一步已經執行過的
currentRegistryProcessors.clear();
// 繼續調用普通的BeanDefinitionRegistryPostProcessors
// 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)) {
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
reiterate = true;
}
}
sortPostProcessors(currentRegistryProcessors, beanFactory);
registryProcessors.addAll(currentRegistryProcessors);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
}
// 最后調用普通的 BeanFactoryPostProcessor,
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
//因為BeanDefinitionRegistryPostProcessor也是繼承了BeanFactoryPostProcessor,,也具有postProcessBeanFactory()方法的,所以也需要執行
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
else {
// 若不是BeanDefinitionRegistry,那就是直接實現了BeanFactoryPostProcessor
// Invoke factory processors registered with the context instance.
invokeBeanFactoryPostProcessors(beanFactoryPostProcessors, beanFactory);
}
// 下面這部分邏輯就和上面套路一樣,無非處理的是BeanFactoryPostProcessor罷了
// 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<>();
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();
}
小結
BeanFactoryPostProcessors是Spring框架中的一個很重要的擴展入口,通過它可以在Bean實例化之前進行一些修改,從類型上分為BeanDefinitionRegistryPostProcessor和BeanFactoryPostProcessor,在內部處理過程中,前者的優先級高於后者。與此同時,他們分別還會按照PriorityOrdered > Ordered > 默認
的優先級順序來進行處理。了解他們執行順序這點很重要,后續如有擴展需求就可以精准植入自己的邏輯。需要注意的是,這些處理器本身就是用於注冊Bean,因此他們也可以注冊和自己類型一樣的擴展類。在使用的時候尤其要注意這點。例如在實現了PriorityOrdered的BeanDefinitionRegistryPostProcessor中
再注冊一個實現了Ordered的BeanDefinitionRegistryPostProcessor,雖然這樣沒問題,但筆者認為這樣代碼隱藏過深。不利於后期維護。建議使用SPI機制來配置,簡潔明了。
registerBeanPostProcessors()
主要用於調用BeanPostProcessors的實現,區別於上一個章節,本章節處理的是實例化過后的Bean。
// AbstractApplicationContext.java
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
// 調用BeanPostProcessor
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
// PostProcessorRegistrationDelegate.java
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
// 獲取所有的BeanPostProcessor名稱
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
// Register BeanPostProcessorChecker that logs an info message when
// a bean is created during BeanPostProcessor instantiation, i.e. when
// a bean is not eligible for getting processed by all BeanPostProcessors.
// 注冊一個BeanPostProcessorChecker,當一個BeanPostProcessor在實例化期間創建一個Bean的時候,打印日志
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
// 按照優先級整理
// 實現了PriorityOrdered接口的BeanPostProcessor集合
List<BeanPostProcessor> priorityOrderedPostProcessors = new ArrayList<>();
// 內部定義的BeanPostProcessor集合
List<BeanPostProcessor> internalPostProcessors = new ArrayList<>();
// 實現了Ordered接口的BeanPostProcessor名稱集合
List<String> orderedPostProcessorNames = new ArrayList<>();
// 未實現排序優先級接口的BeanPostProcessor名稱集合
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);
}
}
// 注冊實現了PriorityOrdered接口的BeanPostProcessor
// First, register the BeanPostProcessors that implement PriorityOrdered.
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// 注冊實現了PriorityOrdered接口的BeanPostProcessor
// Next, register the BeanPostProcessors that implement Ordered.
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);
// 注冊常規的BeanPostProcessor
// 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);
// 重新注冊所有的內部BeanPostProcessor
// Finally, re-register all internal BeanPostProcessors.
sortPostProcessors(internalPostProcessors, beanFactory);
registerBeanPostProcessors(beanFactory, internalPostProcessors);
// 注冊ApplicationListenerDetector,它將在bean初始化完成之后檢測是否為ApplicationListener,如果是則加入applicationListeners中
// 在Bean銷毀之前,提前從ApplicationEventMulticaster中刪除
// Re-register post-processor for detecting inner beans as ApplicationListeners,
// moving it to the end of the processor chain (for picking up proxies etc).
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
initMessageSource()
初始化MessageSource,若當前上下文中未定義,則使用父類中的定義
// AbstractApplicationContext.java
protected void initMessageSource() {
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
else {
// Use empty MessageSource to be able to accept getMessage calls.
DelegatingMessageSource dms = new DelegatingMessageSource();
dms.setParentMessageSource(getInternalParentMessageSource());
this.messageSource = dms;
beanFactory.registerSingleton(MESSAGE_SOURCE_BEAN_NAME, this.messageSource);
if (logger.isTraceEnabled()) {
logger.trace("No '" + MESSAGE_SOURCE_BEAN_NAME + "' bean, using [" + this.messageSource + "]");
}
}
}
initApplicationEventMulticaster()
主要用於設置事件發布器,若當前上下文沒有定義ApplicationEventMulticaster 則使用 SimpleApplicationEventMulticaster
// AbstractApplicationContext.java
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 {
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() + "]");
}
}
}
onRefresh()
當前類中沒有實現,只是作為一個模板,將由子類來實現
// AbstractApplicationContext.java
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
// ServletWebServerApplicationContext.java
protected void onRefresh() {
// 父類中僅僅設置了一下主題,無關緊要
super.onRefresh();
try {
// 創建Web服務器
createWebServer();
}
catch (Throwable ex) {
throw new ApplicationContextException("Unable to start web server", ex);
}
}
創建Web服務器
這里只簡單介紹一下它啟動了內置的Web容器,Web容器的初始化后續會有單獨篇章分析。
private void createWebServer() {
// ①
WebServer webServer = this.webServer;
// ②
ServletContext servletContext = getServletContext();
// ③
if (webServer == null && servletContext == null) {
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
}
// ④
else if (servletContext != null) {
try {
getSelfInitializer().onStartup(servletContext);
}
catch (ServletException ex) {
throw new ApplicationContextException("Cannot initialize servlet context", ex);
}
}
// ⑤
initPropertySources();
}
① - 當前應用的WEB服務器,也就是Servlet容器。
② - 當前應用的上下文,一個應用使用一個ServletContext來表示。
③ - 使用ServletWebServerFactory創建一個Servlet容器
④ - 手動配置上下文的接口。
⑤ - 初始化配置信息,實際上就是將環境信息中的'servletContextInitParams':StubPropertySource 轉換為'servletContextInitParams': ServletContextPropertySource; 將 'servletConfigInitParams': StubPropertySource轉換為'servletConfigInitParams':ServletConfigPropertySource
registerListeners()
主要用於將獲取到的所有監聽器委托給applicationEventMulticaster。
protected void registerListeners() {
// ①
// Register statically specified listeners first.
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!
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);
}
}
}
① - 將內部注冊的監聽器委托給廣播器applicationEventMulticaster。
② - 檢測BeanFactory內部的監聽器
③ - 發布早期事件
finishBeanFactoryInitialization()
實例化剩下的所有單例Bean(非延遲加載的)
// AbstractApplicationContext.java
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// ①
// Initialize conversion service for this context.
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.
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.
beanFactory.freezeConfiguration();
// ⑤
// Instantiate all remaining (non-lazy-init) singletons.
beanFactory.preInstantiateSingletons();
}
① - 判斷是否有轉換服務
② - 判斷是否有占位符解析器
③ - 注冊LoadTimeWeaverAware
④ - 停止使用臨時的ClassLoader進行類型匹配,實際上它就是空值
⑤ - 凍結所有的BeanDefinition,通過configurationFrozen = true 和 frozenBeanDefinitionNames(包含所有的BeanDefinition)配合鎖定
⑥ - 實例化剩下的所有單例Bean(非延遲加載的),其實就是從注冊器緩存里面取出(DefaultSingletonBeanRegistry)
finishRefresh()
// ServletWebServerApplicationContext.java
@Override
protected void finishRefresh() {
// 父類執行finishRefresh
super.finishRefresh();
// 啟動web容器
WebServer webServer = startWebServer();
if (webServer != null) {
// 發布web容器啟動完成事件
publishEvent(new ServletWebServerInitializedEvent(webServer, this));
}
}
// AbstractApplicationContext.java
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.
getLifecycleProcessor().onRefresh();
// ④ Publish the final event.
publishEvent(new ContextRefreshedEvent(this));
// ⑤ Participate in LiveBeansView MBean, if active.
LiveBeansView.registerApplicationContext(this);
}
① - 清除資源緩存
② - 初始化上下文生命周期
③ - 傳播刷新動作至生命周期
④ - 發布上下文刷新完畢事件
⑤ - 構建當前Bean及其依賴關系的快照,設計用於Spring Tool Suite
resetCommonCaches()
主要用於清除Spring內部的緩存
// AbstractApplicationContext.java
protected void resetCommonCaches() {
ReflectionUtils.clearCache();
AnnotationUtils.clearCache();
ResolvableType.clearCache();
CachedIntrospectionResults.clearClassLoader(getClassLoader());
}