Reputation: 1935
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?
Upvotes: 1
Views: 2058
Reputation: 12937
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.
Upvotes: 3
Reputation: 387
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:
Reference: https://www.baeldung.com/spring-boot-lazy-initialization#effects
Upvotes: 5