Junior — Middle
How can deferred initialization of components be implemented in Spring?
sobes.tech AI
Answer from AI
In Spring, lazy initialization of components allows creating beans only upon their first request, rather than at application startup. This helps to speed up startup time and reduce resource consumption.
To implement lazy initialization, you can use the @Lazy annotation:
@Component
@Lazy
public class HeavyComponent {
public HeavyComponent() {
System.out.println("HeavyComponent created");
}
}
If a bean is annotated with @Lazy, Spring will create it only upon the first request from the context.
You can also use @Lazy at the configuration level:
@Configuration
public class AppConfig {
@Bean
@Lazy
public HeavyComponent heavyComponent() {
return new HeavyComponent();
}
}
Additionally, you can inject lazy beans via ObjectProvider or Provider to control the creation moment:
@Autowired
private ObjectProvider<HeavyComponent> heavyComponentProvider;
public void useComponent() {
HeavyComponent component = heavyComponentProvider.getIfAvailable();
// the bean will be created here if it hasn't been already
}
Thus, Spring provides flexible mechanisms for lazy initialization of components.