I am using Spring's @Component
annotation to configure many of the beans in my Spring 3.0 application. I would like to know if it's possible to construct some of these beans lazily - especially the prototype
beans?
@Lazy annotation indicates whether a bean is to be lazily initialized. It can be used on @Component and @Bean definitions. A @Lazy bean is not initialized until referenced by another bean or explicitly retrieved from BeanFactory . Beans that are not annotated with @Lazy are initialized eagerly.
Spring @Bean Annotation is applied on a method to specify that it returns a bean to be managed by Spring context. Spring Bean annotation is usually declared in Configuration classes methods. In this case, bean methods may reference other @Bean methods in the same class by calling them directly.
The reason behind this is simple: to avoid and detect all possible errors immediately rather than at runtime. However, there're cases when we need to create a bean, not at the application context startup, but when we request it. In this quick tutorial, we're going to discuss Spring's @Lazy annotation.
To declare lazy-initialized bean you can use @Lazy
annotation.
Note, however, that it doesn't make sense for prototype
beans - they can't be eagerly initialized, so there is no need to mark them lazy.
Lazy initialization isn't an option in the context of prototype-scoped beans. Those beans are instantiated and initialized on demand every time something asks for them, so they are, by nature, lazily initialized.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With