In this tutorial, we are going to see how to enable Spring Boot Lazy Loading of beans while running the application.

What is Spring Boot Lazy Loading:

Spring Framework has support for lazy bean initialisation since along ago. In spring by default; if the application context being refreshed, every bean in the context will be created, and its dependencies will be injected.

If we enable Spring Boot Lazy Loading, the beans will not be created and it won’t be injected the dependencies while refreshing the application context.

How to Enable Spring Boot Lazy Loading Beans:

Based on your spring boot version number, you can enable Lazy Loading in different ways.

Version:

  • Spring Boot 2.2

Spring Boob 2.2 introduced a new property called spring.main.lazy-initialization. It makes the developer life more comfortable. We can directly add this property to your application.properties or an application.yml file like the following.

application.properties

application.properties
spring.main.lazy-initialization=true

application.yml

application.yml
spring:
  main:
    lazy-initialization: true

If you configure the above feature in your application.properties/yml file; all your beans will be loaded and injected on demand. If you wanted to make some specific beans to Lazy, you have to go with legacy approach like the following.

It is precisely similar to our old approach like the following.

Spring Boot Lazy Loading legacy approach:

If you use the @Lazy annotation on top of the @Configuration class, it says that all the methods with @Bean annotation should be loaded lazily.

AppConfig.java
@Lazy
@Configuration
@ComponentScan(basePackages = "com.onlinetutorialspoint.lazy")
public class AppConfigs {

    @Bean
    public Item getItem(){
        return new Item();
    }

    @Bean
    public Category getCategory(){
        return new Category();
    }
}

If you wanted to make some specific beans as lazy; you should remove the @Lazy annotation from AppConfig class and declare it on top of selected bean methods like the following.

AppConfig.java
@Bean
@Lazy(true)
public Item getItem(){
    return new Item();
}

Spring Boot Lazy Loading with @Autowired:

We can autowire a Lazy bean like the below

Create a Lazy bean first:

AppConfig.java
@Bean
@Lazy
public Category getCategory(){
    return new Category();
}

And refer the category bean like below.

Item.java
public class Item {
    @Lazy
    @Autowired
    Category category;
}

Here the @Lazy annotation is mandatory in both the places.

References:

Happy Learning 🙂