This tutorial will teach you what the @Lazy annotation is and how it is used.
The @Lazy
annotation in Spring Boot is used to mark a bean or component as lazy-initialized. This means that the bean will not be instantiated until it is first requested by another bean or by the user.
@Lazy Annotation Example
To use the @Lazy
annotation, you simply need to add it to the bean definition. In this case, Spring Framework will lazy-initialize one single bean.
Lazy-initialize One Bean
@Configuration public class MyConfiguration { @Lazy @Bean public MyBean myBean() { return new MyBean(); } }
Lazy-initialize All Beans in a Class
Alternatively, you can also apply the @Lazy
annotation to a component class to mark all beans of that type as lazy-initialized:
@Lazy @Component public class MyBean { // ... }
Important Points
There are a few things to keep in mind when using the @Lazy
annotation:
- Lazy-initialized beans are not eligible for dependency injection until they are actually instantiated.
- Lazy-initialized beans are not included in the count of beans that are processed during the application’s startup.
- Lazy-initialized beans may cause a performance hit when they are first accessed, as they must be instantiated at that time.
Overall, the @Lazy
annotation can be useful in cases where you have a bean that is expensive to create and is not needed until later in the application’s lifecycle. It can help improve your application’s startup time by avoiding unnecessary bean instantiations.
To learn more, check out other Spring Boot tutorials.