@Lazy can be used on class or method or field level. It indicates whether a bean is to be initialized lazily. If this annotation is not present on a @Component or @Bean definition, eager initialization will occur.
In addition to using it with @Bean and @Component, this annotation may also be placed on injection points marked with @Autowired or @Inject or @Resource. In that case, the target variable will only be initialize with it's value when used first time.
This example demonstrates the use of @Lazy at the injection point.
package com.logicbig.example;
import jakarta.annotation.PostConstruct;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
public class MyEagerBean {
@Autowired
@Lazy
private MyLazyBean myLazyBean;
@PostConstruct
public void init() {
System.out.println(getClass().getSimpleName() + " has been initialized");
}
public void doSomethingWithLazyBean() {
System.out.println("Using lazy bean");
myLazyBean.doSomething();
}
}
package com.logicbig.example;
import jakarta.annotation.PostConstruct;
public class MyLazyBean {
@PostConstruct
public void init () {
System.out.println(getClass().getSimpleName() + " has been initialized");
}
public void doSomething () {
System.out.println("inside lazy bean doSomething()");
}
}
package com.logicbig.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
public class LazyExampleMain {
public static void main (String[] args) {
ApplicationContext context =
new AnnotationConfigApplicationContext(
MyConfig.class);
System.out.println("--- container initialized ---");
MyEagerBean bean = context.getBean(MyEagerBean.class);
System.out.println("MyEagerBean retrieved from bean factory");
bean.doSomethingWithLazyBean();
}
public static class MyConfig {
@Bean
public MyEagerBean eagerBean () {
return new MyEagerBean();
}
@Bean
@Lazy
public MyLazyBean lazyBean () {
return new MyLazyBean();
}
}
}
Output
MyEagerBean has been initialized
--- container initialized ---
MyEagerBean retrieved from bean factory
Using lazy bean
MyLazyBean has been initialized
inside lazy bean doSomething()
Original Post