liveBook · Manning

Lazy initialization

As explained in Spring Start Here, Second Edition

Lazy instantiation is the creation of an object or bean only when it is first requested or otherwise needed.

Lazy initialization delays creating a Spring singleton bean until it is first requested. By contrast, Spring’s default eager initialization creates singleton beans when the context starts. section 5.1.2

Use `@Lazy` to defer bean creation:

  • Place it on a stereotype-annotated class or on a `@Bean` method. section 5.1.2
  • If nothing requests the bean, it is not created; requesting it triggers creation. section 5.1.2
Listing 5.12 Testing the lazy instantiation
public class Main {
 
  static void main() {
    var c = new AnnotationConfigApplicationContext(ProjectConfig.class);
 
    System.out.println("Before retrieving the CommentService");
    var service = c.getBean(CommentService.class);   #A
    System.out.println("After retrieving the CommentService");
  }
}

The example retrieves CommentService from the context and uses console output to show when its constructor runs. section 5.1.2

How Spring Start Here, Second Edition covers it

How deep it goes
Defines deferred creation and demonstrates its trigger and `@Lazy` configuration, without detailing production tradeoffs.
Examples
Demonstrates a CommentService constructor log and retrieves the bean from an AnnotationConfigApplicationContext.
What you can do after
Operate/configure Spring bean creation on demand with `@Lazy` and trigger it by requesting the bean.
How it connects
Connects lazy initialization to singleton scope, eager instantiation, and the Spring context.

Also explained in

Compare how 12 books explain lazy initialization →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring Start Here, Second Edition. The section links point to the parts of the book it draws on.