Junior — Middle
How to implement a lazy initialization mechanism for a component in Spring?
sobes.tech AI
Answer from AI
In Spring, the lazy initialization mechanism allows beans to be created not at the startup of the context, but only upon the first access to them. This helps optimize application startup time and save resources.
To implement lazy initialization of a component, you can use the @Lazy annotation:
@Component
@Lazy
public class MyComponent {
// component code
}
Alternatively, apply @Lazy to a specific bean in the configuration:
@Bean
@Lazy
public MyComponent myComponent() {
return new MyComponent();
}
You can also enable lazy initialization for the entire context in Spring Boot settings by adding to application.properties:
spring.main.lazy-initialization=true
This will make Spring create all beans lazily, as needed.