Lazy Initialization:
By default in Spring, all the defined beans, and their dependencies, are created when the application context is created. The reason behind this is simple: to avoid and detect all possible errors immediately rather than at runtime.
By default in Spring, all the defined beans, and their dependencies, are created when the application context is created. The reason behind this is simple: to avoid and detect all possible errors immediately rather than at runtime.
In contrast, when we configure a bean with lazy initialization, the bean will only be created, and its dependencies injected, once they're needed.
Enable Lazy Initialization
Setting the property "spring.main.lazy-initialization" value to true means that all the beans in the application will use lazy initialization.
Let's configure the property in our application.yml configuration file:
spring:
spring:
main:
lazy-initialization: true
Or, if it's the case, in our application.properties file:lazy-initialization: true
spring.main.lazy-initialization=true
This configuration affects all the beans in the context. So, if we want to configure lazy initialization for a specific bean, we can do it through the @Lazy approach.
Or in other words, all the defined beans will use lazy initialization, except for those that we explicitly configure with @Lazy(false).
Lazy Initialization With Annotation:
@Configuration Class
When we put @Lazy annotation over the @Configuration class, it indicates that all the methods with @Bean annotation should be loaded lazily.
This is the equivalent for the XML based configuration's default-lazy-init=“true“ attribute.Let's have a look here:@Lazy @Configuration @ComponentScan(basePackages = "com.baeldung.lazy") public class AppConfig { @Bean public Region getRegion(){ return new Region(); } @Bean public Country getCountry(){ return new Country(); } }Then we add it to the config of the desired bean:@Bean @Lazy(true) public Region getRegion(){ return new Region(); }With @Autowired
Here, in order to initialize a lazy bean, we reference it from another one.The bean that we want to load lazily:@Lazy @Component public class City { public City() { System.out.println("City bean initialized"); } }And it's reference:public class Region { @Lazy @Autowired private City city; public Region() { System.out.println("Region bean initialized"); } public City getCityInstance() { return city; } }
Note, that the @Lazy is mandatory in both places.