1

There are two IOC containers in spring-boot: BeanFactory and ApplicationContext.

As per my understanding, ApplicationContext supports the eager initialization of beans where BeanFactory does it lazily.

Problem Statement: In my Spring boot application, I wanna use lazy initialization of beans to make application startup faster. Can anyone please suggest the solution for achieving the same?

2 Answers 2

5

Explanation about Aniket Sahrawat answer: spring.main.lazy-initialization=true

Effects of Lazy Initialization

Enabling lazy initialization in the whole application could produce both positive and negative effects.

Let's talk about some of these, as they're described in the official announcement of the new functionality:

  1. Lazy initialization may reduce the number of beans created when the application is starting – therefore, we can improve the startup time of the application
  2. As none of the beans are created until they are needed, we could mask issues, getting them in run time instead of startup time
  3. The issues can include out of memory errors, misconfigurations, or class-definition-found errors
  4. Also, when we're in a web context, triggering bean creation on demand will increase the latency of HTTP requests – the bean creation will affect only the first request, but this may have a negative impact in load-balancing and auto-scaling.

Reference: https://www.baeldung.com/spring-boot-lazy-initialization#effects

1
3

Use lazy initialization property:

spring.main.lazy-initialization=true

This property is only supported in spring boot 2.2 and above. You will need to write a BeanFactoryPostProcessor if version is less than 2.2. This property will make sure that the dependencies are not to be injected until it's needed, the main difference in timing can be seen when hot restart is performed.

FYI ApplicationContext is a BeanFactory, both supports lazy init. It really depends on when BeanFactory#getBeanProvider was invoked.

3
  • Will this property make the app use the IOC containers as "BeanFactory"? Commented May 22, 2020 at 11:15
  • Could you please add some explanation? Commented May 22, 2020 at 11:21
  • It will use the ApplicationContext. App Context is inherrited from the BeanFactory, enhance it. Default it will load all beans on startup. You can set up BF programmaticly of course, but I suggest use AC in production without lazy loading, so you will see bean creation exceptions on load time. In dev mode, you can use the property, Aniket suggest to you, so the startup time will be decreased.
    – zlaval
    Commented May 22, 2020 at 11:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.