Does Spring Boot Support Lazy Initialization?

Omid Haghighatgoo
2 min readDec 18, 2021

In software development lazy initialization means to postpone any heavy process like object creation or evaluation, calculation a value and etc. until the first usage.

photo by raincarnation40 from pixabay

In this article we want to see what is lazy initialization and if spring boot does support this feature or not? As mentioned above lazy initialization means to postpone any heavy process like object creation, evaluation or calculation a value and etc. until the first usage.

In Spring framework all beans definition with their dependencies will be created when spring application context is created. It is default configuration but there are ways we could change this configuration and we will see these ways in below.

1- Using Spring Configuration File

The first and easiest way (in my opinion) is to change the lazy-initilization property value from false to true in application.properties file or in application.yml file each one you are using as your configuration file in your spring boot project.

2- Using @Lazy Annotation

The second way is to annotate each bean you want to initialize lazy by @Lazy annotation. In this way just the bean you annotate it, will be affected and other beans will work like before.Or If you’ve changed default setting by first method (setting lazy-initializtion property to false) you can use @Lazy(false) for excluding the specific bean.

3- Changing SpringApplication or using SpringApplicationBuilder in main() method

The other way we can choose is to use setLazyInitialization() method of SpringApplication class and sending true parameter to it. In order to do so we need to change our main method in this way:

Sample

For testing above code firstly we would create a simple spring boot project using https://start.spring.io/ or below pom.xml:

result

--

--

Omid Haghighatgoo

Senior Software Engineer with a demonstrated history of working in Information Technology and Services Industry, interested in AI and Machine Learning.