为什么即使bean无法实例化,Spring仍然继续初始化上下文? [英] Why does Spring continue to initialize the context even if a bean fails to instantiate?

查看:170
本文介绍了为什么即使bean无法实例化,Spring仍然继续初始化上下文?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I found a strange spring behavior in instantiating the beans during initial context Loading. I had a bean that loads large ML models. Due to insufficient memory the bean failed to instantiate throwing Out java OutOfMemoryError java heap space exception. But this doesn't stop the application from instantiating, instead it continues to load the application.

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

Why does this happen? Is this expected?

检查弹簧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.

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

Doesn't this affect the application stability? Why is it designed so?
Or am I missing something?

推荐答案

请注意,此处没有catch语句!而且,OutOfMemoryError不是Exception,因此它不会被标准的常规catch (Exception e)捕获.

Notice that there is no catch statement here! Moreover, OutOfMemoryError is not an Exception, so it won't be caught by the standard general catch (Exception e).

使用此finally子句不会捕获Throwable.它必须在其他地方被捕获(已消化).

With this finally clause the Throwable is not caught. It must be caught (digested) somewhere else.

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

Why does Spring continue its work? It's based on a web server, not a standalone dedicated app, why should it stop working immediately? Not all exceptions are critical, even errors can sometimes (... rarely) recovered from. It is the programmer's duty to ensure all "his" throwables are properly handled, not Spring's.

这篇关于为什么即使bean无法实例化,Spring仍然继续初始化上下文?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆