Wednesday, 20 April 2016

What is Lazy instantiation ? How to configure Lazy instantiation of the bean ?


The default behavior for ApplicationContext implementations is to eagerly pre-instantiate all singleton beans at startup.
Pre-instantiation means that an ApplicationContext will eagerly create and configure all of its singleton beans as part of its initialization process.

If you do not want a singleton bean to be pre-instantiated when using an ApplicationContext, you can selectively control this by marking a bean definition as lazy-initialized. A lazily-initialized bean indicates to the IoC container whether or not a bean instance should be created at startup or when it is first requested.
When configuring beans via XML, this lazy loading is controlled by the 'lazy-init' attribute on the <bean/> element.
Example
<bean id="lazy" class="com.foo.ExpensiveToCreateBean"
      lazy-init="true" />
<bean name="notlazy" class="com.foo.AnotherBean"/>

When the above configuration is consumed by an ApplicationContext, the bean named 'lazy' will not be eagerly pre-instantiated when the ApplicationContext is starting up, whereas the 'notlazy' bean will be eagerly pre-instantiated.

Note :  Even though a bean definition may be marked up as being lazy-initialized, if the lazy-initialized bean is the dependency of a singleton bean that is not lazy-initialized, when the ApplicationContext is eagerly pre-instantiating the singleton, it will have to satisfy all of the singletons dependencies, one of which will be the lazy-initialized bean !
So don't be confused if the IoC container creates one of the beans that you have explicitly configured as lazy-initialized at startup; all that means is that the lazy-initialized bean is being injected into a non-lazy-initialized singleton bean elsewhere.

It is also possible to control lazy-initialization at the container level by using the 'default-lazy-init' attribute on the <beans/> element
Example
<beans default-lazy-init="true">
    <!-- no beans will be pre-instantiated... -->
</beans>

No comments:

Post a Comment

Note: only a member of this blog may post a comment.