目录
上节中已经讲过AnnotationConfigApplicationContext中初始化了reader,用于加载6个Bean。主要是Processor,我们称之为后置处理器。处理器主要的使用就是在refresh方法中。
refresh方法
refresh方法是Spring ApplicationContext的精髓,ioc,aop都是在此中完成。此方法是在AbstractApplicationContext实现的,子类可以覆盖重写父类中的方法。例如Spring Boot中ServletWebServerApplicationContext 就是覆盖了onRefresh方法,完成refresh方法后启动webServer的功能。
通过阅读refresh方法,可以看出通过使用synchronized加锁,调用类内不同的方法,完成以下工作:属性配置注入,BeanFactory准备,BeanFactory后置处理器调用,注册beanPostProcessor,初始化国际化及事件注册器,完成BeanFactory,完成refresh方法。
@Override
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
准备工作包括设置启动时间,是否激活标识位,
// 初始化属性源(property source)配置
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//返回一个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.
// org.springframework.web.context.support.GenericWebApplicationContext.postProcessBeanFactory
// org.springframework.web.context.support.StaticWebApplicationContext.postProcessBeanFactory
//这个方法在当前版本的spring是没用任何代码的
//可能spring期待在后面的版本中去扩展吧
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//在spring的环境中去执行已经被注册的 factory processors
//设置执行自定义的ProcessBeanFactory 和spring内部自己定义的
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.
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();
}
}
}