Why does Spring continue to initialize the context even if a bean fails to instantiate?

浪子不回头ぞ 提交于 2019-12-24 02:36:04

问题


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?

checked the spring 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);
}

It digests the exception silently with comment // Finished partial creation of this bean.

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


回答1:


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).

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

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.



来源:https://stackoverflow.com/questions/18656936/why-does-spring-continue-to-initialize-the-context-even-if-a-bean-fails-to-insta

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!