xxxxxxxxxx
@Lazy
@Configuration
@ComponentScan(basePackages = "com.baeldung.lazy")
public class AppConfig {
@Bean
public Region getRegion(){
return new Region();
}
@Bean
public Country getCountry(){
return new Country();
}
}
xxxxxxxxxx
// By default all beans are eagerly loaded (Beans are automatically initialized on the launch of application)
// Recommended : Use eager loading (Reason : Errors in spring configuration can be identified early if there is any)
// Use case : If there are too many beans that you need to stop loading early to speed up application launching process
// Use Scope : Annotation can be used anywhere you can use "@Bean" or "@Component" annotations
@Component
class ClassA {
// Business Logic
}
@Component
@Lazy // THIS IS WHAT IS RESPONSIBLE FOR LAZY LOADING : will only load when any bean of this class is needed
class ClassB {
@SuppressWarnings("unused")
private ClassA classA;
public ClassB(ClassA classA) {
System.out.println("Some Initialization logic");
this.classA = classA;
}
public void doSomething() { System.out.println("Do Something");}
}
@Configuration
@ComponentScan
public class LazyInitializationLauncherApplication {
public static void main(String[] args) {
try (var context =
new AnnotationConfigApplicationContext
(LazyInitializationLauncherApplication.class)) {
System.out.println("Initialization of context is completed"); // All eager loaded beans are created by this point
context.getBean(ClassB.class).doSomething(); // Only now the lazy bean of ClassB will be loaded since it was called
}
}
}