Spring @Lazy Annotation Example
In this section we will learn about @Lazy Annotation. By default, the Spring IoC container creates and initializes all singleton beans at time of application startup. This default behavior ensures that any possible error caught immediately. This feature is really good to avoid any runtime errors but there are a number of use cases when we do not want Spring IoC to create beans on startup but create it when requested by the application. We can prevent this pre-initialization of a singleton bean by using the @Lazy annotation. The @Lazy annotation may be used on any class annotated with @Component , @Service & @Repository or on methods annotated with @Bean . 1. Using @Lazy on @Bean method If @Lazy annotation present on a @Bean method, Spring initializes that specific bean lazily. Let’s have a look at example. In following example, we have configured 2 beans and SMSService bean marked with @Lazy . public class EmailService { public EmailService () { ...