关联博文:
AbstractApplicationContext中refresh方法详解
Spring中refresh分析之prepareRefresh方法详解
Spring中refresh分析之obtainFreshBeanFactory方法详解
Spring中refresh分析之prepareBeanFactory方法详解
————————————————
Spring中refresh分析之postProcessBeanFactory方法详解
Spring中refresh分析之invokeBeanFactoryPostProcessors方法详解
Spring中refresh分析之registerBeanPostProcessors方法详解
Spring中refresh分析之initMessageSource方法详解
Spring中refresh分析之initApplicationEventMulticaster方法详解
Spring中refresh分析之onRefresh方法详解
Spring中refresh分析之registerListeners方法详解
Spring中refresh分析之finishBeanFactoryInitialization方法详解
Spring中refresh分析之finishRefresh方法详解
接上文AbstractApplicationContext中refresh方法详解我们分析过prepareRefresh后,本文分析obtainFreshBeanFactory方法。
该方法主要是获取到应用上下文维护的beanFactory,默认是DefaultListableBeanFactory 。
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory(); // AbstractApplicationContext protected ConfigurableListableBeanFactory obtainFreshBeanFactory() { refreshBeanFactory(); return getBeanFactory(); }
① refreshBeanFactory
GenericApplicationContext
的refreshBeanFactory
方法。其首先应用CAS思想设置刷新标志,然后为beanFactory设置序列化ID-默认是application。
@Override protected final void refreshBeanFactory() throws IllegalStateException { if (!this.refreshed.compareAndSet(false, true)) { throw new IllegalStateException( "GenericApplicationContext does not support multiple refresh attempts: just call 'refresh' once"); } this.beanFactory.setSerializationId(getId()); }
当前对象this指的是AnnotationConfigServletWebServerApplicationContext,而refreshBeanFactory调用是其传递祖父类GenericApplicationContext 。GenericApplicationContext 内部如下所示维护了beanFactory。
public class GenericApplicationContext extends AbstractApplicationContext implements BeanDefinitionRegistry { private final DefaultListableBeanFactory beanFactory; @Nullable private ResourceLoader resourceLoader; private boolean customClassLoader = false; private final AtomicBoolean refreshed = new AtomicBoolean(); public GenericApplicationContext() { this.beanFactory = new DefaultListableBeanFactory(); } //... }
② getBeanFactory
这里调用的仍旧是GenericApplicationContext的方法,如下所示,只是返回了内部维护的beanFactory,默认是DefaultListableBeanFactory。
@Override public final ConfigurableListableBeanFactory getBeanFactory() { return this.beanFactory; }
GenericApplicationContext关于BeanDefinition的行为比如get、remove,其实就是交给了beanFactory来处理。