Senior
How does the @Lazy annotation work under the hood?
sobes.tech AI
Answer from AI
The @Lazy annotation in Spring is used for deferred initialization of beans. Under the hood, it works as follows:
- When the Spring context loads, it does not create the bean immediately but instead creates a proxy object.
- This proxy delays the actual creation and initialization of the bean until the first time it is accessed.
- When the application first requests the bean, the proxy initializes the real object and hands over control to it.
Thus, @Lazy helps optimize application startup time and resources by creating beans only when necessary.
Example:
@Component
@Lazy
public class HeavyService {
public HeavyService() {
System.out.println("HeavyService initialized");
}
}
In this example, HeavyService will not be created at context startup but only upon the first call from another component.