spring高级容器ApplicationContext之ref
我们在上节spring高级容器之ApplicationContext文章中对applicationContext容器的功能简单的了解下,我们还遗留了一个问题就是#refresh()方法的作用,可以说该方法为applicationContext容器的核心方法,也是我们值得学习的一个方法,接下来让我们来一起学习该方法,代码如下:
/**
* 加载或者刷新配置方法(重要)
* @throws BeansException
* @throws IllegalStateException
*/
void refresh() throws BeansException, IllegalStateException;
上述是该方法的定义,在ConfigurableApplicationContext类中,我们其实根据方法名就能简答的猜出该方法的用处,就是用来刷新当前spring所处的上下文,我们接着看该方法的具体的实现过程,代码如下:
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
//准备刷新上下文
prepareRefresh();
//创建并初始化beanFactory
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//装配beanFactory
prepareBeanFactory(beanFactory);
try {
//在当前上下文环境下对beanFactory进行后置处理操作
postProcessBeanFactory(beanFactory);
//激活各种BeanFactory的处理器
invokeBeanFactoryPostProcessors(beanFactory);
//注册拦截Bean创建的Bean处理器,即注册BeanPostProcessor
registerBeanPostProcessors(beanFactory);
//为上下文环境初始化MessageSource,即不同语言的消息体,国际化处理操作
initMessageSource();
//初始化上下文事件广播器
initApplicationEventMulticaster();
//此处是留给子类来初始化其他的bean
onRefresh();
//在所有bean中查找listener bean,然后注册到广播器中
registerListeners();
//初始化剩下的单例Bean(非延迟加载的)
finishBeanFactoryInitialization(beanFactory);
//完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人
finishRefresh();
}
catch (BeansException ex) {
if (logger.isWarnEnabled()) {
logger.warn("Exception encountered during context initialization - " +
"cancelling refresh attempt: " + ex);
}
//销毁已经创建的单例bean
destroyBeans();
// Reset 'active' flag.
cancelRefresh(ex);
// 抛异常
throw ex;
}
finally {
// Reset common introspection caches in Spring's core, since we
// might not ever need metadata for singleton beans anymore...
resetCommonCaches();
}
}
}
接下来我们分别来看看上述代码中的方法,注意:很重要
prepareRefresh()
该方法其主要的作用是对上下文环境的初始化准备工作,如对系统环境或者系统属性变量的准备验证过程,这个变量的设置可能会影响着系统的正确性,我们可以通过重写initPropertySources方法就可以了,代码如下:
/**
* 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();
//设置当前上下文(Context)的状态
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.
// 初始化context environment(上下文环境)中的占位符属性来源
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<>();
}
该方法主要做了以下几件事:
- 对当前上下文进行状态的设置.
- 初始化 context environment 中占位符.
- 当前环境的一些校验等.
对于beanFactory的初始化
/**
* Tell the subclass to refresh the internal bean factory.
* @return the fresh BeanFactory instance
* @see #refreshBeanFactory()
* @see #getBeanFactory()
*/
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
refreshBeanFactory();
return getBeanFactory();
}
其真正的核心逻辑处理方法为refreshBeanFactory(),接着看:
AbstractRefreshableApplicationContext.java
/**
* 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 {
//进行判断,若存在,销毁该beanFactory下的所有bean,并对其关闭处理
if (hasBeanFactory()) {
destroyBeans();
closeBeanFactory();
}
try {
//创建DefaultListableBeanFactory对象
DefaultListableBeanFactory beanFactory = createBeanFactory();
//设置序列化编码
beanFactory.setSerializationId(getId());
//定制BeanFactory设置相关属性
customizeBeanFactory(beanFactory);
//加载beanDefinition
loadBeanDefinitions(beanFactory);
//将beanFactory设置为当前环境下的beanFactory
synchronized (this.beanFactoryMonitor) {
this.beanFactory = beanFactory;
}
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}}
简单的来看下上述的过程:
- 首先是对当前容器的判断,如果已存在beanFactory则将其移除该beanFactory创建的bean和移除自身
- 接着是调用#createBeanFactory()方法来创建beanFactory实例
- 给beanfactory设置序列化id
- 加载beanDefinition
- 将创建好的 bean 工厂的引用交给的 context 来管理
prepareBeanFactory(beanFactory)
/**
* 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为当前上下文的classLoader
beanFactory.setBeanClassLoader(getClassLoader());
//设置beanFactory的表达式语言处理器
//默认可以使用#{bean.xxx}的形式来调用相关属性值
beanFactory.setBeanExpressionResolver(new StandardBeanExpressionResolver(beanFactory.getBeanClassLoader()));
//为beanFactory增加一个默认的PropertyEditor,主要是针对bean的属性等设置管理统一的一个tool
beanFactory.addPropertyEditorRegistrar(new ResourceEditorRegistrar(this, getEnvironment()));
// Configure the bean factory with context callbacks.
//添加beanPostProcessor
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 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);
// 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.
// 注册默认的系统环境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设置各种各样的功能
postProcessBeanFactory(beanFactory)
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
是在AbstractApplicationContext里是空实现,该方法允许子类覆盖去实现,我们接着看:
#AbstractRefreshableWebApplicationContext.java
protected void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
beanFactory.addBeanPostProcessor(new ServletContextAwareProcessor(this.servletContext, this.servletConfig));
beanFactory.ignoreDependencyInterface(ServletContextAware.class);
beanFactory.ignoreDependencyInterface(ServletConfigAware.class);
WebApplicationContextUtils.registerWebApplicationScopes(beanFactory, this.servletContext);
WebApplicationContextUtils.registerEnvironmentBeans(beanFactory, this.servletContext, this.servletConfig);
}
我们可以在子类AbstractRefreshableWebApplicationContext看到了实现的过程,简单的看一下流程:
- 首先是添加ServletContextAwareProcessor到我们的beanFactory容器中,其中processor 实现 BeanPostProcessor 接口,主要用于将ServletContext 传递给实现了 ServletContextAware 接口的 bean.
- 忽略一些装配接口ServletContextAware和ServletConfigAware等.
- 注册 WEB 应用特定的域(scope)到 beanFactory 中,方便WebApplicationContext 可以使用它们,常见的有: request session response application等.
- 注册 WEB 应用特定的 Environment bean 到 beanFactory 中,以便WebApplicationContext 可以使用它们,常见的有:contextAttributes等.
invokeBeanFactoryPostProcessors(beanFactory)
public static void invokeBeanFactoryPostProcessors(
ConfigurableListableBeanFactory beanFactory, List<BeanFactoryPostProcessor> beanFactoryPostProcessors) {
// Invoke BeanDefinitionRegistryPostProcessors first, if any.
//processedBeans用来保存所有的beanFactoryPostProcessor
Set<String> processedBeans = new HashSet<>();
//如果当前的beanFactory为BeanDefinitionRegistry
if (beanFactory instanceof BeanDefinitionRegistry) {
//强转为BeanDefinitionRegistry类型的
BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;
//BeanFactoryPostProcessor的集合
List<BeanFactoryPostProcessor> regularPostProcessors = new ArrayList<>();
List<BeanDefinitionRegistryPostProcessor> registryProcessors = new ArrayList<>();
//遍历处理过程
for (BeanFactoryPostProcessor postProcessor : beanFactoryPostProcessors) {
//如果是BeanDefinitionRegistryPostProcessor实例
if (postProcessor instanceof BeanDefinitionRegistryPostProcessor) {
BeanDefinitionRegistryPostProcessor registryProcessor =
(BeanDefinitionRegistryPostProcessor) postProcessor;
//添加到registryProcessors集合中
registryProcessor.postProcessBeanDefinitionRegistry(registry);
registryProcessors.add(registryProcessor);
}
//如果不是BeanDefinitionRegistryPostProcessor,则保存到regularPostProcessors集合中
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.
//用于保存临时的BeanDefinitionRegistryPostProcessor
List<BeanDefinitionRegistryPostProcessor> currentRegistryProcessors = new ArrayList<>();
// First, invoke the BeanDefinitionRegistryPostProcessors that implement PriorityOrdered.
//首先处理实现了 PriorityOrdered (有限排序接口)的 BeanDefinitionRegistryPostProcessor
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
//遍历处理
for (String ppName : postProcessorNames) {
//将ConfigurableListableBeanFactory和PriorityOrdered进行匹配
if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
//添加
currentRegistryProcessors.add(beanFactory.getBean(ppName, BeanDefinitionRegistryPostProcessor.class));
processedBeans.add(ppName);
}
}
//排序
sortPostProcessors(currentRegistryProcessors, beanFactory);
//保存到registryProcessors集合中
registryProcessors.addAll(currentRegistryProcessors);
//调用所有实现了PriorityOrdered的BeanDefinitionRegistryPostProcessors的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);
invokeBeanDefinitionRegistryPostProcessors(currentRegistryProcessors, registry);
currentRegistryProcessors.clear();
// Finally, invoke all other BeanDefinitionRegistryPostProcessors until no further ones appear.
//最后是调用其他的BeanDefinitionRegistryPostProcessors
boolean reiterate = true;
while (reiterate) {
reiterate = false;
//通过bean的类型去获取BeanDefinitionRegistryPostProcessor
postProcessorNames = beanFactory.getBeanNamesForType(BeanDefinitionRegistryPostProcessor.class, true, false);
for (String ppName : postProcessorNames) {
//没有包含在processedBeans中的(因为包含了的都已经处理了)
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();
}
// Now, invoke the postProcessBeanFactory callback of all processors handled so far.
//调用所有的BeanFactoryPostProcessors(这里只包含我们手动注册的)
invokeBeanFactoryPostProcessors(registryProcessors, beanFactory);
invokeBeanFactoryPostProcessors(regularPostProcessors, beanFactory);
}
//如果不是BeanDefinitionRegistry 只需要调用其回调函数(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!
String[] postProcessorNames =
beanFactory.getBeanNamesForType(BeanFactoryPostProcessor.class, true, false);
// Separate between BeanFactoryPostProcessors that implement PriorityOrdered,
// Ordered, and the rest.
//这里需要区分PriorityOrdered和Ordered和no Ordered
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
}
//PriorityOrdered类型
else if (beanFactory.isTypeMatch(ppName, PriorityOrdered.class)) {
priorityOrderedPostProcessors.add(beanFactory.getBean(ppName, BeanFactoryPostProcessor.class));
}
//Ordered类型的
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
//nonOrdered类型的
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
// First, invoke the BeanFactoryPostProcessors that implement PriorityOrdered.
//首先是调用priorityOrderedPostProcessors接口
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(priorityOrderedPostProcessors, beanFactory);
// Next, invoke the BeanFactoryPostProcessors that implement Ordered.
//接着是Ordered接口
List<BeanFactoryPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
for (String postProcessorName : orderedPostProcessorNames) {
orderedPostProcessors.add(beanFactory.getBean(postProcessorName, BeanFactoryPostProcessor.class));
}
sortPostProcessors(orderedPostProcessors, beanFactory);
invokeBeanFactoryPostProcessors(orderedPostProcessors, beanFactory);
// Finally, invoke all other BeanFactoryPostProcessors.
//最后是nonOrdered接口处理
List<BeanFactoryPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
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();
}
上述代码其主要的作用是激活beanFactory的各种处理器,代码有点长,其整个处理逻辑简单清晰,都是对所有的BeanDefinitionRegistryPostProcessors按照PriorityOrdered以及Ordered和ordered的分别处理过程.
registerBeanPostProcessors
该方法主要的作用是注册所有的注册所有的BeanPostProcessor,来看代码:
protected void registerBeanPostProcessors(ConfigurableListableBeanFactory beanFactory) {
PostProcessorRegistrationDelegate.registerBeanPostProcessors(beanFactory, this);
}
这里并看不到真正的处理过程,接着看:
public static void registerBeanPostProcessors(
ConfigurableListableBeanFactory beanFactory, AbstractApplicationContext applicationContext) {
//获取所有BeanPostProcessor的beanName
//此时的bean是未进行初始化操作,但已经加载到容器中
String[] postProcessorNames = beanFactory.getBeanNamesForType(BeanPostProcessor.class, true, false);
//记录所有beanPostProcessor的数量
int beanProcessorTargetCount = beanFactory.getBeanPostProcessorCount() + 1 + postProcessorNames.length;
//注册BeanPostProcessorChecker,其主要的作用是在bean的实例化期间进行日志的记录
//
beanFactory.addBeanPostProcessor(new BeanPostProcessorChecker(beanFactory, beanProcessorTargetCount));
//通过PriorityOrdered来保证顺序
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实例
BeanPostProcessor pp = beanFactory.getBean(ppName, BeanPostProcessor.class);
priorityOrderedPostProcessors.add(pp);
if (pp instanceof MergedBeanDefinitionPostProcessor) {
internalPostProcessors.add(pp);
}
}
//保存到有序的orderedPostProcessorNames缓存中
else if (beanFactory.isTypeMatch(ppName, Ordered.class)) {
orderedPostProcessorNames.add(ppName);
}
//保存到无序的缓存中
else {
nonOrderedPostProcessorNames.add(ppName);
}
}
//第一步,注册所有实现了 PriorityOrdered 的 BeanPostProcessor
//首先是排序
sortPostProcessors(priorityOrderedPostProcessors, beanFactory);
//接着是注册
registerBeanPostProcessors(beanFactory, priorityOrderedPostProcessors);
// Next, register the BeanPostProcessors that implement Ordered.
//第二步,注册所有实现Ordered接口的BeanPostProcessor
List<BeanPostProcessor> orderedPostProcessors = new ArrayList<>(orderedPostProcessorNames.size());
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.
//第三步,注册所有没有排序的BeanPostProcessor
List<BeanPostProcessor> nonOrderedPostProcessors = new ArrayList<>(nonOrderedPostProcessorNames.size());
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.
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(探测器)
beanFactory.addBeanPostProcessor(new ApplicationListenerDetector(applicationContext));
}
这里将注册的逻辑委托给PostProcessorRegistrationDelegate来实现,具体的就不在啰嗦了,接着看
initMessageSource
该方法主要是为上下文环境初始化MessageSource,即不同语言的消息体,国际化处理操作,我们来看代码:
protected void initMessageSource() {
//获取并初始化beanFactory
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//如果在beanFactory包含messageSource的bean
if (beanFactory.containsLocalBean(MESSAGE_SOURCE_BEAN_NAME)) {
//直接获取通过getBean(...)方法
this.messageSource = beanFactory.getBean(MESSAGE_SOURCE_BEAN_NAME, MessageSource.class);
// Make MessageSource aware of parent MessageSource.
//如果有父类并且是HierarchicalMessageSource类型的
if (this.parent != null && this.messageSource instanceof HierarchicalMessageSource) {
//强转为HierarchicalMessageSource
HierarchicalMessageSource hms = (HierarchicalMessageSource) this.messageSource;
if (hms.getParentMessageSource() == null) {
// Only set parent context as parent MessageSource if no parent MessageSource
// registered already.
//如果没有注册父 MessageSource,则设置为父类上下文的的 MessageSource
hms.setParentMessageSource(getInternalParentMessageSource());
}
}
if (logger.isTraceEnabled()) {
logger.trace("Using MessageSource [" + this.messageSource + "]");
}
}
//这里是beanFactory不包含messageSource该bean
else {
// Use empty MessageSource to be able to accept getMessage calls.
//使用空的MessageSource去接受message
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 + "]");
}
}
}
代码逻辑简单,根据获取到的beanFactorey来区分,如果包含messageSource的bean进行相应的处理,没有的使用空的MessageSource来进行消息的处理,接着看:
initApplicationEventMulticaster
该方法的主要作用是为当前上下文来初始化一个事件广播器,我们来看代码:
/**
* Initialize the ApplicationEventMulticaster.
* Uses SimpleApplicationEventMulticaster if none defined in the context.
* @see org.springframework.context.event.SimpleApplicationEventMulticaster
*/
protected void initApplicationEventMulticaster() {
//获取ConfigurableListableBeanFactory从BeanFactory中
ConfigurableListableBeanFactory beanFactory = getBeanFactory();
//如果包含applicationEventMulticaster类型的bean
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 + "]");
}
}
//没有则新建SimpleApplicationEventMulticaster,并完成 bean的注册
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
该方法主要是留给子类拓展方法,用来完成其他bean的上下文刷新操作
/**
* Template method which can be overridden to add context-specific refresh work.
* Called on initialization of special beans, before instantiation of singletons.
* <p>This implementation is empty.
* @throws BeansException in case of errors
* @see #refresh()
*/
protected void onRefresh() throws BeansException {
// For subclasses: do nothing by default.
}
所以是空实现喽
registerListeners
该方法其主要的作用是为当前上下文注册一个事件监听器,至于监听器从何而来,是在所有的bean中去找,那么注册到哪呢?则是广播器中,我们来看代码:
/**
* Add beans that implement ApplicationListener as listeners.
* Doesn't affect other listeners, which can be added without being beans.
*/
protected void registerListeners() {
// 首先是注册静态监听器
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...
//至此,已经完成将监听器注册到ApplicationEventMulticaster中,下面将发布前期的事件给监听器
Set<ApplicationEvent> earlyEventsToProcess = this.earlyApplicationEvents;
this.earlyApplicationEvents = null;
if (earlyEventsToProcess != null) {
for (ApplicationEvent earlyEvent : earlyEventsToProcess) {
getApplicationEventMulticaster().multicastEvent(earlyEvent);
}
}
}
finishBeanFactoryInitialization
该方法主要的作用是初始化剩下的单例Bean(非延迟加载的),来看代码:
/**
* Finish the initialization of this context's bean factory,
* initializing all remaining singleton beans.
*/
protected void finishBeanFactoryInitialization(ConfigurableListableBeanFactory beanFactory) {
// 给当前上下文初始化转换器服务
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.
//如果之前没有注册 bean 后置处理器(例如PropertyPlaceholderConfigurer),则注册默认的解析器
if (!beanFactory.hasEmbeddedValueResolver()) {
beanFactory.addEmbeddedValueResolver(strVal -> getEnvironment().resolvePlaceholders(strVal));
}
// 尽早初始化LoadTimeWeaverAware bean以允许尽早注册其变换器
String[] weaverAwareNames = beanFactory.getBeanNamesForType(LoadTimeWeaverAware.class, false, false);
for (String weaverAwareName : weaverAwareNames) {
getBean(weaverAwareName);
}
// 停止使用临时的 ClassLoader
beanFactory.setTempClassLoader(null);
// 允许缓存所有bean定义元数据
beanFactory.freezeConfiguration();
// 初始化所有剩余的单例(非延迟的).
beanFactory.preInstantiateSingletons();
}
finishRefresh
该方法为refresh的最后一个方法其主要的作用是完成刷新过程,通知生命周期处理器lifecycleProcessor刷新过程,同时发出ContextRefreshEvent通知别人,我们来看代码:
/**
* 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.
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);
}
我们可以看到的在方法finishRefresh()中是做了一些完成上下文刷新后的工作,就像代码中的清空资源缓存以及初始化生命周期等等操作,那么本节到这里就完了,关于APPlicationContext高级容器我们就说这么多,下节我们来说spring的另一个很吊的作用AOP...