Skip to content

Instantly share code, notes, and snippets.

@qqyycom
Created August 27, 2018 14:53
Show Gist options
  • Save qqyycom/6e4c8042e53f5070ddd42d9da102767f to your computer and use it in GitHub Desktop.
Save qqyycom/6e4c8042e53f5070ddd42d9da102767f to your computer and use it in GitHub Desktop.
springBean的生命周期
public abstract class AbstractApplicationContext extends DefaultResourceLoader
implements ConfigurableApplicationContext {
//每次refresh会destory Beanfactory中已经初始化的对象
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
prepareRefresh();
// ,刷新beanFactory(如果没有,就创建一个)从配置文件或配置类中读取beanName,beanDefinition等信息,并注册到beanFactory中
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
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.\
// 初始化所有实现了BeanPostProcessor接口的类
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.
// 初始化bean
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();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment