javaspringlazy-initialization

Are there any real downsides to lazy bean initialization?


Recently I've started using the lazy initialization feature in spring a lot. And so I've been wandering - are there any actual downsides to initializing your beans lazily? If not - why is not lazy the default behaviour?


Solution

  • The primary "downside" is not catching configuration issues immediately. If you have a bean that is only used "occasionally", and that bean is misconfigured, your application could be out in production for several days before it goes to use that bean and throws the error. It's much better to know about that issue at startup.

    Additionally, it is generally more desirable to pay initialization costs (i.e. performance, time delays, etc.) at startup rather than during use. In a Web Application for example, you want the cost of initializing the bean at startup, not the first time a customer uses your shopping cart (waiting for the shopping cart bean to do its first initialization), and then again when she goes to checkout, and then again when payment is processed, etc.

    Those are some of the reasons.

    [EDIT]

    p.s. from the Spring reference guide section 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.