In this post we will learn about the lazy initialization of spring beans using attribute lazy-init and default-lazy-init.By default spring container will create all the singleton bean at container startup i.e when the spring container is loaded.This is necessary since if there is any error in creating the beans or setting the dependencies will be known to us at the container load time itself.But sometimes we don't need this behavior.We would like to create the bean only when it is requested and not at the container startup,thus reducing the container startup time.
Below code example will show how to lazy initialize the bean.
Employee- Spring bean which we will lazy initialize.
LazyInitDemo - Main class which load the container and initializes the bean.
Studentcontext.xml - metadata configuration details for the spring container.
Employee.java
employeecontext.xml
As we can see in the application context file,we set the attribute lazy-init to true in the bean definition.This will make this bean to be create only when it is requested and not at the container load time.
LazyInitDemo.java
OUTPUT:
When we run LazyInitDemo class, we will get the below output
As we can see in the output,employee bean was not created at container loaded time and was created only when it was requested.
when we need all the beans defined in the application context to be lazy initialized,use the attribute default-lazy-init in the parent "beans" tag as shown below
Below code example will show how to lazy initialize the bean.
Employee- Spring bean which we will lazy initialize.
LazyInitDemo - Main class which load the container and initializes the bean.
Studentcontext.xml - metadata configuration details for the spring container.
Employee.java
employeecontext.xml
As we can see in the application context file,we set the attribute lazy-init to true in the bean definition.This will make this bean to be create only when it is requested and not at the container load time.
LazyInitDemo.java
OUTPUT:
When we run LazyInitDemo class, we will get the below output
As we can see in the output,employee bean was not created at container loaded time and was created only when it was requested.
when we need all the beans defined in the application context to be lazy initialized,use the attribute default-lazy-init in the parent "beans" tag as shown below
No comments:
Post a Comment