Spring @Lazy Annotation Example

In this tutorial,  we will learn how to use @Lazy annotation in Spring or Spring boot applications.

YouTube Video

@Lazy Annotation Overview

By default, Spring creates all singleton beans eagerly at the startup/bootstrapping of the application context.

You can load the Spring beans lazily (on-demand) using @Lazy annotation. 

The @Lazy annotation can be used with @Configuration, @Component, and @Bean annotations.

Eager initialization is recommended: to avoid and detect all possible errors immediately rather than at runtime.

@Lazy Annotation Example

Let's create two classes and annotated them with @Component annotation.

EagerLoader

import org.springframework.stereotype.Component;

@Component
public class EagerLoader {

    public EagerLoader(){
        System.out.println("EagerLoader ..");
    }
}

LazyLoader

Note that we have annotated LazyLoader class with @Lazy annotation:
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

@Component
@Lazy
public class LazyLoader {

    public LazyLoader(){
        System.out.println("LazyLoader..");
    }
}

Testing

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringAnnotationsApplication {

	public static void main(String[] args) {
		var context = SpringApplication.run(SpringAnnotationsApplication.class, args);
		// EagerLoader eagerLoader = context.getBean(EagerLoader.class);
                LazyLoader lazyLoader = context.getBean(LazyLoader.class);
	}
}

Note that the EagerLoader class bean was created eagerly at the startup/bootstrapping of the application context but the LazyLoader class bean is created when it requested using the getBean() method:

                LazyLoader lazyLoader = context.getBean(LazyLoader.class);

This clearly demonstrates that @Lazy annotation is used to load the Spring beans lazily (on-demand).

Using @Value Annotation with @Configuration & @Bean Annotations

If you annotated @Lazy annotation with @Configuration annotation then all the beans within the configuration file are loaded lazily:

import net.javaguides.springannotations.lazy.EagerLoader;
import net.javaguides.springannotations.lazy.LazyLoader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;

@Configuration
@Lazy
public class AppConfig {

    @Bean
    public LazyLoader lazyLoader(){
        return new LazyLoader();
    }

    @Bean
    public EagerLoader eagerLoader(){
        return new EagerLoader();
    }
}

If you annotated @Lazy annotation with @Bean annotation then that particular bean within the configuration file is loaded lazily:

    @Bean
    @Lazy
    public LazyLoader lazyLoader(){
        return new LazyLoader();
    }

Related Spring and Spring Boot Annotations

Comments