- When you create a bean definition what you are actually creating is a recipe for creating actual instances of the class defined by that bean definition. The idea that a bean definition is a recipe is important, because it means that, just like a class, you can potentially have many object instances created from a single recipe.
- You can control not only the various dependencies and configuration values that are to be plugged into an object that is created from a particular bean definition, but also the scope of the objects created from a particular bean definition. This approach is very powerful and gives you the flexibility to choose the scope of the objects you create through configuration instead of having to ‘bake in’ the scope of an object at the Java class level. Beans can be defined to be deployed in one of a number of scopes: out of the box, the Spring Framework supports exactly five scopes (of which three are available only if you are using a Web-aware ApplicationContext).
The scopes supported out of the box are listed as follows:
- singleton: Scopes a single bean definition to a single object instance per Spring IoC container.
-
prototype: Scopes a single bean definition to any number of object instances.
-
request: Scopes a single bean definition to the lifecycle of a single HTTP request; that is each and every HTTP request will have its own instance of a bean created off the back of a single bean definition. Only valid in the context of a Web-aware Spring ApplicationContext.
-
session: Scopes a single bean definition to the lifecycle of a HTTP Session. Only valid in the context of aWeb-aware Spring ApplicationContext.
-
global session: Scopes a single bean definition to the lifecycle of a global HTTP session. Typically only valid when used in a portlet context. Only valid in the context of a Web-aware Spring ApplicationContext.
The singleton Scope
- When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
- To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.
- Please be aware that Spring’s concept of a singleton bean is quite different from the Singleton pattern as defined in the seminal Gang of Four (GoF) patterns book. The GoF Singleton hardcodes the scope of an object such that one and only one instance of a particular class will ever be created per ClassLoader. The scope of theS pring singleton is best described as per container and per bean. This means that if you define one bean for a particular class in a single Spring container, then the Spring container will create one and only one instance of the class defined by that bean definition. The singleton scope is the default scope in Spring. To define a bean as a singleton in XML, you would write configuration like so:

<!-- the following is equivalent, though redundant (singleton scope is the default); using spring-beans-2.0.dtd -->
<bean id="accountService"
class="com.foo.DefaultAccountService" scope="singleton"/>
<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="true"/>
The prototype Scope
- The non-singleton, prototype scope of bean deployment results in the creation of a new bean instance every time a request for that specific bean is made (that is, it is injected into another bean or it is requested via a programmatic getBean() method call on the container). As a rule of thumb, you should use the prototype scope for all beans that are stateful, while the singleton scope should be used for stateless beans.
- The following diagram illustrates the Spring prototype scope. Please note that a DAO would not typically be configured as a prototype, as a typical DAO would not hold any conversational state; it was just easier for this author to reuse the core of the singleton diagram.

To define a bean as a prototype in XML, you would write configuration like so:
<!-- using spring-beans-2.0.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" scope="prototype"/>
<!-- the following is equivalent and preserved for backward compatibility in spring-beans.dtd -->
<bean id="accountService" class="com.foo.DefaultAccountService" singleton="false"/>
- There is one quite important thing to be aware of when deploying a bean in the prototype scope, in that the lifecycle of the bean changes slightly. Spring does not manage the complete lifecycle of a prototype bean: the container instantiates, configures, decorates and otherwise assembles a prototype object, hands it to the client and then has no further knowledge of that prototype instance. This means that while initialization lifecycle callback methods will be called on all objects regardless of scope, in the case of prototypes, any configured destruction lifecycle callbacks will not be called.
- It is the responsibility of the client code to clean up prototype scoped objects and release any expensive resources that the prototype bean(s) are holding onto. (One possible way to get the Spring container to release resources used by prototype-scoped beans is through the use of a custom bean post-processor which would hold a reference to the beans that need to be cleaned up.)
Other Bean Scope
The other scopes, namely request, session, and global session are for use only in Web-based applications (and can be used irrespective of which particular Web application framework you are using, if indeed any).

Item.Java
package com.javaskool;
public class Item {
private int itemId;
private String itemName;
private int qty;
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="obj" class="com.javaskool.Item" scope="singleton">
<property name="itemId" value="1001"/>
<property name="itemName" value="Mouse"/>
<property name="qty" value="500"/>
</bean>
<!-- OR , Since By default singleton
<bean id="obj" class="com.javaskool.Item">
<property name="itemId" value="1001"/>
<property name="itemName" value="Mouse"/>
<property name="qty" value="500"/>
</bean>
-->
</beans>
TestDrive.java
package com.javaskool;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class TestDrive {
public static void main(String[] args)
{
Resource res = new ClassPathResource("applicationContext.xml");
BeanFactory beans=new XmlBeanFactory(res);
Item p1=(Item)beans.getBean("obj"); //getting first Object from BeanFactory
Item p2=(Item)beans.getBean("obj"); //getting second Object from BeanFactory
System.out.println(p1==p2); //Will Return true since both are same object
System.out.println(p1.getItemId());
System.out.println(p1.getItemName());
System.out.println(p1.getQty());
}
}
Output
true
1001
Mouse
500
Item.Java
package com.javaskool;
public class Item {
private int itemId;
private String itemName;
private int qty;
public int getItemId() {
return itemId;
}
public void setItemId(int itemId) {
this.itemId = itemId;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="obj" class="com.javaskool.Item" scope="prototype">
<property name="itemId" value="1001"/>
<property name="itemName" value="Mouse"/>
<property name="qty" value="500"/>
</bean>
</beans>
TestDrive.java
package com.javaskool;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
public class TestDrive {
public static void main(String[] args)
{
Resource res = new ClassPathResource("applicationContext.xml");
BeanFactory beans=new XmlBeanFactory(res);
Item p1=(Item)beans.getBean("obj"); //getting first Object from BeanFactory
Item p2=(Item)beans.getBean("obj"); //getting second Object from BeanFactory
System.out.println(p1==p2); //Will Return false since both are different object
System.out.println(p1.getItemId());
System.out.println(p1.getItemName());
System.out.println(p1.getQty());
}
}
Output
false
1001
Mouse
500
Download Examples
Click Below to download the Examples
Recent Comments