lazy-init concept

Whenever the spring container object is created based on application context it creates all the spring beans and establish the dependencies for all the beans whose scope attribute is default/singleton.

lazy-init:

This attribute takes either of the two values "true" or "false". By default it uses "false". When we specify lazy-init="false" and scope="singleton", the spring container creates the spring bean object immediately. If lazy-init="true" and scope="singleton", whenever the spring container object is created it will not create the spring bean object. It does this work whenever we call the getBean() method.
The way to define lazy-init and scope is given in the below applicationContext.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
 xmlns:p="http://www.springframework.org/schema/p"
 xsi:schemaLocation="http://www.springframework.org/schema/beans 
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
 
 <bean id="addr" class="com.ram.beans.Address" lazy-init="true" scope="singleton">
  <property name="street" value="Richmond"></property>
  <property name="city" value="Melbourne"></property>
  <property name="state" value="Victoria"></property>
 </bean>
 
</beans>
 <bean id="addr" class="com.ram.beans.Address" lazy-init="true" scope="prototype">
 ...
</beans>

Note: If scope="prototype" then lazy-init is ineffective, that means whatever may be the value of lazy-int, spring bean object will be created.

No comments:

Post a Comment