How to Enable Lazy Initialization for Spring Beans to Boost Startup Performance
This article explains Spring's default eager bean creation, demonstrates how to add @Lazy annotations or a global property to defer bean instantiation until needed, and discusses the benefits and drawbacks of lazy loading with code examples and runtime observations.
1. Bean Initialization
By default Spring creates an instance for every @Component bean at startup, so all beans are ready to use. The article demonstrates this by adding a print statement in the constructor of each Coach implementation and showing the startup logs where all four implementations are instantiated.
2. @Lazy Lazy Loading
Lazy loading means a bean is initialized only when it is injected or directly called. Adding the @Lazy annotation to a class defers its creation. The example adds @Lazy to TrackCoach:
@Lazy
@Component
public class TrackCoach implements Coach {
public TrackCoach() {
System.out.println("In constructor: " + getClass().getSimpleName());
}
}The controller uses only CricketCoach, so TrackCoach never initializes at startup:
@RestController
public class FunRestController {
private Coach coach;
@Autowired
public FunRestController(@Qualifier("cricketCoach") Coach coach) {
this.coach = coach;
}
@GetMapping("/workout")
public String getDailyWorkout() {
return coach.getDailyWorkout();
}
}Instead of annotating each bean, a global lazy‑initialization can be enabled with the property: spring.main.lazy-initialization=true After setting this property, none of the Coach implementations nor the FunRestController are instantiated until the /workout endpoint is called, which then triggers initialization of the controller and CricketCoach:
When dependencies are injected, the dependent bean is created after its dependencies, so initialization order matters.
Advantages and Disadvantages of Lazy Loading
Save resources: objects are created only when needed.
Faster startup, especially when the application contains many components.
Drawbacks:
Web components such as @RestController are instantiated only after a request, which can hide configuration problems.
Issues may be discovered later, making troubleshooting harder.
All beans must have sufficient space for creation when they are finally needed.
Consequently, global lazy loading is disabled by default and should be enabled only when its benefits outweigh the potential drawbacks.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
