Spring Boot 2.2.0 : Quicker startup times with Lazy Initialization

Sai Pitchuka
3 min readOct 22, 2019

Spring Boot 2.2.0 comes with a handy feature which can be utilized to reduce the application start up time by deferring the bean creations and dependency injections to later time thereby quickening the application start up time.

Spring beans creation will be initiated only when needed by Lazy initializing the bean creation and dependency injections.

Lazy Initialization is already possible in previous versions of spring boot but then to enable lazy initialization one need to implement BeanFactoryPostProcessor. Spring boot 2.2.0 offers a simple way to enable lazy initialization of beans.

There is a property added newly that will enable/disable lazy initialization

spring.main.lazy-initialization

Setting the above property to true will enable the lazy initialization of beans.

Let us try with one example:

Create a sample spring boot project as given below from https://start.spring.io/

Generate the project and unzip and open from IDE.

Now, create a sample rest controller as below.

Notice that I have added a constructor too with a print statement to help check when Controller is initialized.

Now let’s start the application and check the constructor print statement in the console output.

The constructor print statement of the Controller is present in the console output indicating that bean initialization is done during start up which is the default behavior.

Let’s start the application by setting lazy initialization enabled i.e by adding the property spring.main.lazy-initialization=true

The constructor print statement is not present in console output indicating bean is not created at start up.

Now, try to access the end point in the Controller which we created earlier and that action should initialize the Controller.

Accessing the rest endpoint created earlier. Now, check the console output and the bean constructor print statement would appear after accessing the rest endpoint(as highlighted in the below image) indicating lazy initialization of bean.

Alternatively lazy initialization can be enabled/disabled with the help of equivalent methods in SpringApplication. Highlighted in the below image.

There are few considerations in using the lazy initialization feature.

It is mostly appropriate to use only in development phase of the application which can help the developer to quickly test code changes because of reduced start up times. It is a not advised to be used in production as by using Lazy Initialization any issues in bean initialization cannot be caught at start up time

Please visit my YouTube channel https://youtube.com/channel/UC-8tqCyhtt6Lt5-n2UMZB_A

--

--