Spring Boot Lazy Initialization Example

Lazy Bean’s initialization is not a new topic for Spring developers.

The spring framework supports lazy-init from over 10 years.

By enabling lazy loading ( lazy-init="true" ) for a bean, we tell spring container to not to create that bean until it’s needed.

So, what is new in the spring boot lazy initialization feature that is introduced in the spring boot 2.0 version?.

What is new in Spring Boot Lazy Initialization

To understand the benefits of lazy initialization, let’s create a demo on spring lazy initialization.

At first, go to spring initializr and generate a new project. Don’t forget to select spring boot 2.2.0 M4 version.

Lazy Initialization in Spring Boot
Generate Spring Boot Project

Now download and extract this project and import it in eclipse or STS.

After importing the project, create two new packages and classes for controllers and services.

Project Structure

Inside LazyController.java

LazyService.java

Now let’s run the application to see how long it takes to start our application.

As you could see in the above logs, our application took 1535 ms to initialize and 2.472 seconds to start the app.

Did you observe that even we haven’t called REST api /api/welcome, but spring container still initialized LazyService?

Sometimes it is not a good idea to initialize bean until it is used.

Therefore, How can we improve the performance of the above code?

Let’s optimize the above program using spring boot lazy initialization.

To enable lazy initialization, open application.properties and below code

And re-run the program.

From the above logs, it is clear that spring took only 1493 ms initialization, and 2.227seconds to start the application.

You may think that there is not a huge difference in application startup.

But if there are many controllers, services, config classes are present then you will find a significant difference.

Additionally, if you notice LazyService and LazyController are not yet called.

Not let’s hit API from the browser.

in my case it is http://localhost:8080/api/welcome .

As you can see, once you hit API, then only spring container will initialize process service.

Enable Lazy Initialization using @Lazy

If you don’t want to enable lazy initialization for all classes. You can also use @Lazy annotation.

In the above LazyController class, we have annotated LazyService property with @Lazy.

Also, we have an annotated Service class with @Lazy.

Let’s re-run the application

Now, you can see that only LazyService is not initialized now.

One thought on “Spring Boot Lazy Initialization Example”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.