spring refresh()源码解析
时间: 2023-11-13 17:04:39 浏览: 36
refresh()方法是ApplicationContext接口中定义的方法,它的实现在AbstractApplicationContext抽象类中。
下面是refresh()方法的源码解析:
```
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()方法主要分为以下几个步骤:
1.调用prepareRefresh()方法,准备刷新应用程序上下文。
2.调用obtainFreshBeanFactory()方法,创建或获取新的BeanFactory。BeanFactory是Spring的Bean容器,它负责管理Bean的生命周期。
3.调用prepareBeanFactory()方法,对BeanFactory进行一些准备工作,例如设置类加载器、添加属性编辑器等。
4.调用postProcessBeanFactory()方法,允许子类在BeanFactory初始化完成后对BeanFactory进行进一步的处理。
5.调用invokeBeanFactoryPostProcessors()方法,对注册在应用程序上下文中的BeanFactoryPostProcessor进行处理。
6.调用registerBeanPostProcessors()方法,注册BeanPostProcessor,这些BeanPostProcessor用于在Bean实例化之后执行一些操作。
7.调用initMessageSource()方法,初始化消息源,用于国际化。
8.调用initApplicationEventMulticaster()方法,初始化事件广播器,用于事件的发布和监听。
9.调用onRefresh()方法,允许子类在应用程序上下文刷新完成后执行一些特殊的操作。
10.调用registerListeners()方法,注册事件监听器。
11.调用finishBeanFactoryInitialization()方法,实例化所有的singleton bean。
12.调用finishRefresh()方法,完成应用程序上下文的刷新。
13.如果在刷新过程中出现异常,会调用destroyBeans()方法销毁已经创建的singleton Bean,然后抛出异常。