Spring bean Lazy loading xml configuration example

The Spring bean Lazy loading xml configuration example show you how can lazy initialize spring beans. Spring container eagerly creates and configures all singleton beans by default. If your bean configuration is wrong Spring container throws errors and exceptions at startup time. However, you can lazy initialize spring beans at runtime by marking the bean definition as lazy-initialized. This will not create the bean immediately but create the instance when it is first requested.

Create Spring Beans
In this Spring bean Lazy loading xml configuration example, we create two beans Student and Book.

Student bean

Book bean

Lazy Initialize Spring Bean

Our two beans will be loading in spring container. The bean Student will be loaded eagerly by default. The bean Book will be lazy initialized by setting the lazy-init attribute of the element. See the below spring bean configuration:

By setting the attribute lazy-init=”true”, the container will lazy initialized this bean instead of loading eagerly. It means that the bean will be created when it is first requested.

Demo Application
In this Spring bean Lazy loading xml configuration example, We create the main class to bootstrap the application. We print the message after context loaded and retrieve an instance of Book bean. However, both of Student and Book beans are loaded, let’s see the below:

Running the above main and see the output. You will see the bean Student is loaded eagerly and the bean Book is lazy loaded.

One more thing, if a lazy-initialized bean is a dependency of another bean that is not lazy-initialized, the spring container must make sure the singleton’s dependencies so that it must creates the lazy-initialized bean at startup. Now we will discuss other example to classify this issues.

We add a Course bean that has a dependency which is Book bean like below

then configure the dependency of Course bean in spring-config.xml

Running the above main again and see the output. You will see all the beans is loaded eagerly via the below message:

That’s all on the Spring bean Lazy loading xml configuration example.

References
Lazy init beans Spring Doc

Download complete source code, click link below

spring-bean-lazy-loading-xml-configuration-example.zip (28 downloads)

If you found this useful, please share it with your friends

Leave a Comment

*

Please share it if you found this useful
Hide Buttons