Does your Spring application take too long to start? Maybe this annotation could help you.
This annotation indicates to Spring that a bean needs to be lazily initiated.
Spring will not create this bean at the start of the application. Instead, it will create it only when the bean is requested for the first time.
This allows Spring start-up to be faster. However, the first interaction with the bean can be slow because of the time required to create and inject the bean at runtime.
You can use this annotation directly in the bean class (beans annotated with @Component and other stereotypes). Also, it can be used in methods annotated with @Bean.
It’s possible to annotate a @Configuration class, making all the beans from that class become lazily initiated.
Let’s see some examples of how to use it.
1. Using @Lazy Directly in the Class
@Service
@Lazy
public class EmailService {
public void sendEmail(String message) {
System.out.println("Sending email with message: " + message);
}
}
2. Using @Lazy in a Bean Method
@Configuration
public class AppConfig {
@Bean
@Lazy
public EmailService emailService() {
return new EmailService();
}
}
3. Using @Lazy with a @Configuration Class
@Lazy
@Configuration
public class AppConfig {
@Bean
public EmailService emailService() {
return new EmailService();
}
}
Use Case Scenarios for @Lazy Annotation
This annotation can be useful when you are working with some beans that are resource-intensive to create.
You could use this annotation, so they don’t affect the startup of your application, making the application become available fast by not loading this bean at the start-up.
Remember this decision is a trade-off, your application may start faster, but it will slow down the resource that uses this resource-intensive bean, in the first usage. Spring will setup the bean that was not created at the application start-up.
Another scenario is to use this annotation in beans that are rarely used.
Let’s say your application has an EmailService
that needs to send emails once a week.
You won’t need this right away, so it’s fine to set this bean with lazy initialization.
Conclusion
Now you understand how to use @Lazy in your project. Can you find places on your application that you can apply it? Share your thoughts and let me know in the comments!
If you like this topic, make sure to follow me. In the following days, I’ll be explaining more about Spring annotations! Stay tuned!