obtainFreshBeanFactory 方法的会在 org.springframework.context.support.AbstractApplicationContext.refresh() 方法中被调用,该方法调用没有参数,返回值类型 org.springframework.beans.factory.config.ConfigurableListableBeanFactory,实现功能是创建一个 bean 工厂并将其返回。
源码
protected ConfigurableListableBeanFactory obtainFreshBeanFactory() {
// 抽象方法,子类可以实现该方法,创建自定义的 bean 工厂实例
refreshBeanFactory();
// 抽象方法,需要子类实现,返回自定义的 bean 工厂实例
return getBeanFactory();
}
refreshBeanFactory 方法在 org.springframework.context.support.AbstractRefreshableApplicationContext 中的实现
protected final void refreshBeanFactory() throws BeansException {
// 判断当前是否已经有 bean 工厂实例存在
if (hasBeanFactory()) {
// 销毁所有的 bean 工厂中的 bean 实例
destroyBeans();
// 关闭 bean 工厂并释放其资源
closeBeanFactory();
}
try {
// 创建 bean 工厂实例,默认 bean 工厂实例类型为
// org.springframework.beans.factory.support.DefaultListableBeanFactory.DefaultListableBeanFactory
DefaultListableBeanFactory beanFactory = createBeanFactory();
// 设置 serializationId 用于 bean 工厂实例的序列化
beanFactory.setSerializationId(getId());
// 子类可以重写该方法自定义 bean 工厂
customizeBeanFactory(beanFactory);
// 抽象方法,用于加载 bean 定义,子类需要实现该方法
loadBeanDefinitions(beanFactory);
// 将创建的 bean 工厂实例赋值实例属性方便后续使用
this.beanFactory = beanFactory;
}
catch (IOException ex) {
throw new ApplicationContextException("I/O error parsing bean definition source for " + getDisplayName(), ex);
}
}
getBeanFactory 方法在 org.springframework.context.support.AbstractRefreshableApplicationContext 中的实现
public final ConfigurableListableBeanFactory getBeanFactory() {
DefaultListableBeanFactory beanFactory = this.beanFactory;
if (beanFactory == null) {
throw new IllegalStateException("BeanFactory not initialized or already closed - " +
"call 'refresh' before accessing beans via the ApplicationContext");
}
return beanFactory;
}
至此,已经将 org.springframework.context.support.AbstractApplicationContext.refresh() 方法中的 obtainFreshBeanFactory 方法实现已经讲解完毕,有什么疑问可以在评论区进行留言