liveBook · Manning

@lazy annotation

As explained in Spring Start Here, Second Edition

The @Lazy annotation is a Spring annotation that configures a bean for lazy instantiation.

A Spring bean is normally created when the application context starts, even if nothing uses it. @Lazy defers creation until the bean is requested. section 5.1.2

Listing 5.11 Configuring lazy instantiation
@Service
@Lazy   #A
public class CommentService {
 
  public CommentService() {
    System.out.println("CommentService instance created!");
  }
}

Place @Lazy on a stereotype-annotated class to defer its bean’s creation; the annotation can also go on a @Bean method. section 5.1.2

When creation happens

A lazy CommentService produces no constructor output at startup if unused. Retrieving it from the context triggers creation. Eager instantiation is generally more convenient: it avoids checks when beans delegate to one another and exposes creation problems at startup. section 5.1.2

How Spring Start Here, Second Edition covers it

How deep it goes
Shows annotation placement and creation timing, then compares performance and error-detection tradeoffs with eager instantiation.
Examples
Demonstrates an unused CommentService and its constructor output before and after retrieval from the context.
What you can do after
Configure a Spring bean to instantiate only when requested by adding @Lazy to its class or @Bean method.
How it connects
Connects lazy instantiation with eager instantiation and bean retrieval from the Spring application context.

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.