目录
refresh概述
在AbstractApplicationContext中,refresh方法如下:
public void refresh() throws BeansException, IllegalStateException {
synchronized(this.startupShutdownMonitor) {
this.prepareRefresh();
ConfigurableListableBeanFactory beanFactory = this.obtainFreshBeanFactory();
this.prepareBeanFactory(beanFactory);
try {
this.postProcessBeanFactory(beanFactory);
this.invokeBeanFactoryPostProcessors(beanFactory);
this.registerBeanPostProcessors(beanFactory);
this.initMessageSource();
this.initApplicationEventMulticaster();
this.onRefresh();
this.registerListeners();
this.finishBeanFactoryInitialization(beanFactory);
this.finishRefresh();
} catch (BeansException var9) {
if (this.logger.isWarnEnabled()) {
this.logger.warn("Exception encountered during context initialization - cancelling refresh attempt: " + var9);
}
this.destroyBeans();
this.cancelRefresh(var9);
throw var9;
} finally {
this.resetCommonCaches();
}
}
}
prepareRefresh方法
源码如下:
protected void prepareRefresh() {
this.startupDate = System.currentTimeMillis();
this.closed.set(false);
this.active.set(true);
if (this.logger.isDebugEnabled()) {
if (this.logger.isTraceEnabled()) {
this.logger.trace("Refreshing " + this);
} else {
this.logger.debug("Refreshing " + this.getDisplayName());
}
}
this.initPropertySources();
this.getEnvironment().validateRequiredProperties();
if (this.earlyApplicationListeners == null) {
this.earlyApplicationListeners = new LinkedHashSet(this.applicationListeners);
} else {
this.applicationListeners.clear();
this.applicationListeners.addAll(this.earlyApplicationListeners);
}
this.earlyApplicationEvents = new LinkedHashSet();
}
作用:
- 设置容器启动时间
- 设置活跃状态为true
- 设置关闭状态为false
- 获取Environment对象,并加载当前系统的属性值到Environment中
- 准备监听器和事件的集合对象,默认为空
问题1:为什么需要设置容器活跃状态?
首先,spring是个框架,容器的创建和销毁都由spring自身所管理。然而,spring是高度扩展的,这意味着开发人员可以在任意时间对容器进行操作。
假如开发人员在扩展代码时,手动加入代码:
applicationContext.refresh();
这将会导致applicationContext进行没必要的重启。
此外,avtive属性被设置为AtomicBoolean类型,也可以保证多线程下的竞争安全问题
问题2:监听器的作用是什么,为什么spring中的监听器默认为空?
监听器的作用是处理异步消息,spring中的监听器虽然默认为空,但是提供了扩展的方法。比如使用springboot启动时,就会默认加上14个对应监听器,如:LoggingApplicationListener
obtainFreshBeanFactory方法
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
this.refreshBeanFactory();
return this.getBeanFactory();
}
其中refreshBeanFatory()的主要方法包括:
- createBeanFactory (创建Bean工厂)
- customizeBeanFactory (定制化Bean工厂)
- loadBeanDefinitions (加载Bean定义信息)
prepareBeanFactory方法
正在学习中...