Bean lifecycle and scopes · Topic 4 of 5
Lazy initialization
Definition​
By default Spring creates every singleton at startup, so mistakes show up immediately. A @Lazy bean is created only when it is first needed. It speeds up startup but moves any failure to run time.
Example code​
When each bean is created
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
class Report {
Report(String name) { System.out.println("creating " + name); }
}
@Configuration
class AppConfig {
@Bean
Report eager() { return new Report("eager report"); } // created at startup
@Bean
@Lazy
Report lazy() { return new Report("lazy report"); } // created on first use
}
class Demo {
public static void main(String[] args) {
try (var context = new AnnotationConfigApplicationContext(AppConfig.class)) {
System.out.println("context started");
context.getBean("lazy"); // first use: now it is created
}
}
}
// Output:
// creating eager report
// context started
// creating lazy report
Finished this page? Track your progress (saved only in your browser).