Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating lazily initialized Spring beans using annotation based configuration

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?

like image 806
teabot Avatar asked Mar 02 '10 18:03

teabot


People also ask

How do you use lazy annotation in Spring?

@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.

Which annotation is used to initialize a bean in Spring?

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.

Why is @lazy annotation is used?

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.


2 Answers

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.

like image 88
axtavt Avatar answered Oct 08 '22 00:10

axtavt


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.

like image 43
skaffman Avatar answered Oct 08 '22 01:10

skaffman