@Lazy Annotation in Spring: What It Is and How It Works
@Lazy annotation in Spring delays the creation of a bean until it is first needed, instead of creating it at application startup. This helps improve startup time and resource use by initializing beans only when required.How It Works
The @Lazy annotation tells Spring to wait before creating a bean. Normally, Spring creates all singleton beans when the application starts. But with @Lazy, Spring holds off until the bean is actually requested.
Think of it like ordering food at a restaurant. Usually, the kitchen prepares all dishes as soon as the restaurant opens (eager loading). Using @Lazy is like waiting to cook a dish only when a customer orders it (lazy loading). This saves resources and time if some dishes (beans) are never ordered (used).
This mechanism works by creating a proxy for the bean. When your code asks for the bean, the proxy triggers the real bean creation at that moment.
Example
This example shows a Spring bean marked with @Lazy. The bean is not created at startup but only when requested.
import org.springframework.context.annotation.*; import org.springframework.stereotype.Component; @Configuration class AppConfig { @Bean @Lazy public ExpensiveService expensiveService() { System.out.println("Creating ExpensiveService bean"); return new ExpensiveService(); } } @Component class ExpensiveService { public ExpensiveService() { // Simulate expensive setup } public void serve() { System.out.println("Service is running"); } } public class LazyDemo { public static void main(String[] args) { AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class); System.out.println("Context started"); // Bean is created only here, when first requested ExpensiveService service = context.getBean(ExpensiveService.class); service.serve(); context.close(); } }
When to Use
Use @Lazy when you want to speed up application startup by delaying creation of beans that are costly to create and might not be needed immediately or at all.
Common cases include:
- Beans that connect to external systems or databases and are expensive to initialize.
- Beans used only in rare scenarios or specific user actions.
- Large applications where startup time matters and some beans can wait.
This helps save memory and CPU during startup and improves overall app responsiveness.
Key Points
@Lazydelays bean creation until first use.- Improves startup time and resource use.
- Works by creating a proxy that triggers real bean creation.
- Best for expensive or rarely used beans.
- Can be applied at bean or injection point level.