【问题标题】:Why does Spring continue to initialize the context even if a bean fails to instantiate?为什么即使 bean 实例化失败,Spring 也会继续初始化上下文?
【发布时间】:2013-09-06 11:37:30
【问题描述】:

我在初始上下文加载期间实例化 bean 时发现了一个奇怪的弹簧行为。我有一个加载大型 ML 模型的 bean。由于内存不足,bean 无法实例化抛出 java OutOfMemoryError java 堆空间异常。 但这不会阻止应用程序实例化,而是继续加载应用程序。

为什么会这样?这是预期的吗?

检查了弹簧AbstractAutowireCapableBeanFactory

try {
    // Mark this bean as currently in creation, even if just partially.
    beforeSingletonCreation(beanName);
    // Give BeanPostProcessors a chance to return a proxy instead of the target bean instance.
    instance = resolveBeforeInstantiation(beanName, mbd);
    if (instance == null) {
        bw = createBeanInstance(beanName, mbd, null);
        instance = bw.getWrappedInstance();
    }
}
finally {
    // Finished partial creation of this bean.
    afterSingletonCreation(beanName);
}

它通过注释 // Finished partial creation of this bean. 默默地消化异常

这不会影响应用程序的稳定性吗?为什么会这样设计?
还是我错过了什么?

【问题讨论】:

    标签: java spring autowired spring-bean


    【解决方案1】:

    注意这里没有catch语句!而且OutOfMemoryError不是Exception,所以不会被标准通用catch (Exception e)抓到。

    有了这个finally 子句,Throwable 就不会被捕获。它必须在其他地方捕获(消化)。

    为什么 Spring 继续它的工作?它基于 Web 服务器,而不是独立的专用应用程序,为什么要立即停止工作?并非所有异常都是关键的,有时甚至可以(...很少)从中恢复错误。确保正确处理所有“他的”可抛出对象是程序员的职责,而不是 Spring 的。

    【讨论】:

      猜你喜欢
      • 2017-03-17
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多