惰性 bean 初始化有什么真正的缺点吗?

Are there any real downsides to lazy bean initialization?

最近我开始在spring中大量使用惰性初始化功能。所以我一直在徘徊——懒惰地初始化你的豆子有什么实际的缺点吗?如果不是 - 为什么不是懒惰的默认行为?

主要 "downside" 没有立即发现配置问题。如果您有一个仅使用 "occasionally" 的 bean,并且该 bean 配置错误,则您的应用程序可能会在生产环境中停运几天,然后才能使用该 bean 并抛出错误。最好在启动时了解该问题。

此外,通常更希望在启动时而不是在使用期间支付初始化成本(即性能、时间延迟等)。例如,在 Web 应用程序中,您需要在启动时初始化 bean 的成本,而不是在客户第一次使用您的购物车时(等待购物车 bean 进行首次初始化),然后在她结账时再次使用,然后在处理付款时再次出现,等等。

这些是一些原因。

[编辑]

p.s。来自 Spring 参考指南部分 6.4.4 Lazy-initialized beans

By default, ApplicationContext implementations eagerly create and configure all singleton beans as part of the initialization process. Generally, this pre-instantiation is desirable, because errors in the configuration or surrounding environment are discovered immediately, as opposed to hours or even days later. When this behavior is not desirable, you can prevent pre-instantiation of a singleton bean by marking the bean definition as lazy-initialized. A lazy-initialized bean tells the IoC container to create a bean instance when it is first requested, rather than at startup.