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











