Uncategorized

SCOPE OF BEANS IN SPRING FRAMEWORK

Every Bean is associated with a scope.When you make a getBean(“bean Id”) call spring container determines which bean to return using the scope of the bean.The default scope of every bean is singleton and there are total 4 types of scope of a bean.

Types of scope of a bean:

  1. Singleton
  2. Prototype
  3. request
  4. session
  5. globalSession

To define scope we have to add an attribute¬†scope=”name of scope” in the bean tag.

NOTE: request, session, and globalsession are related to Spring MVC, So we will cover them later in our tutorials.

Let’s understand the concept of scope with an example

Product.java


package com.codegeekslab.product;

public abstract class Product {
private String name;
private float price;

public float getPrice() {
return price;
}

public void setPrice(float price) {
this.price = price;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

@Override
public String toString() {
return "Chips [name=" + name + ", price=" + price + "]";
}
}

Book.java


package com.codegeekslab.items;

import com.codegeekslab.product.Product;

public class Book extends Product {

private String author;

public String getAuthor() {
return author;
}

public void setAuthor(String author) {
this.author = author;
}

@Override
public String toString() {
return "Book [author=" + author + "]";
}

}

Chips.java


package com.codegeekslab.items;

import com.codegeekslab.product.Product;

public class Chips extends Product {

private String flavour;

public String getFlavour() {
return flavour;
}

public void setFlavour(String flavour) {
this.flavour = flavour;
}

@Override
public String toString() {
return "Chips [flavour=" + flavour + "]";
}

}

ShoppingCart.java


package com.codegeekslab.cart;

import java.util.ArrayList;
import java.util.List;

import com.codegeekslab.product.Product;

public class ShoppingCart {
private List<Product> items = new ArrayList<Product>();

public void addItem(Product item) {
items.add(item);
}

public List<Product> getItems() {
return items;
}
}

beans.xml


<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.5.xsd">

<bean id="book" class="com.codegeekslab.items.Book">
<property name="name" value="Rich dad Poor dad" />
<property name="price" value="14" />
<property name="author" value="robert kiyosaki" />
</bean>
<bean id="chips" class="com.codegeekslab.items.Chips">
<property name="name" value="Lays" />
<property name="price" value="2" />
<property name="flavour" value="mexican" />

</bean>
<bean id="chips2" class="com.codegeekslab.items.Chips">
<property name="name" value="uncle chips" />
<property name="price" value="2" />
<property name="flavour" value="indian" />

</bean>
<bean id="shoppingCart" class="com.codegeekslab.cart.ShoppingCart" />
</beans>

Test.java


package com.codegeekslab.test;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.GenericXmlApplicationContext;

import com.codegeekslab.cart.ShoppingCart;
import com.codegeekslab.product.Product;

public class Test {

public static void main(String[] args) {
ApplicationContext context = new GenericXmlApplicationContext("beans.xml");
Product item1 = (Product) context.getBean("book");
Product item2 = (Product) context.getBean("chips");
Product item3 = (Product) context.getBean("chips2");
ShoppingCart cart1 = (ShoppingCart) context.getBean("shoppingCart");
cart1.addItem(item1);
cart1.addItem(item2);
System.out.println("Shopping cart 1 contains " + cart1.getItems());
ShoppingCart cart2 = (ShoppingCart) context.getBean("shoppingCart");
cart2.addItem(item3);
System.out.println("Shopping cart 2 contains " + cart2.getItems());


}
}

output


Mar 30, 2017 11:18:54 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Mar 30, 2017 11:18:55 PM org.springframework.context.support.GenericXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericXmlApplicationContext@5e9f23b4: startup date [Thu Mar 30 23:18:55 IST 2017]; root of context hierarchy
Shopping cart 1 contains [Book [author=robert kiyosaki], Chips [flavour=mexican]]
Shopping cart 2 contains [Book [author=robert kiyosaki], Chips [flavour=mexican], Chips [flavour=indian]]

Here in this example if you look into beans.xml you can see i have defind 3 beans for 3 different products.first one is of class book name as “Rich dad poor dad”,second one and third are of class chips named as “lays” and “uncle chips” respectivley.


<bean id="book" class="com.codegeekslab.items.Book">
<property name="name" value="Rich dad Poor dad" />
<property name="price" value="14" />
<property name="author" value="robert kiyosaki" />
</bean>
<bean id="chips" class="com.codegeekslab.items.Chips">
<property name="name" value="Lays" />
<property name="price" value="2" />
<property name="flavour" value="mexican" />

</bean>
<bean id="chips2" class="com.codegeekslab.items.Chips">
<property name="name" value="uncle chips" />
<property name="price" value="2" />
<property name="flavour" value="indian" />

And the 4th bean is of ShoppingCart class which will help us to add all these products into a cart.


</bean>
<bean id="shoppingCart" class="com.codegeekslab.cart.ShoppingCart" />
</beans>

Now in our Test.java i have created beans of all the three products and named them as item1,item2 and item3 and then i have created the 2 carts by creating beans of ShoppingCart class named as “cart1” and “cart2” respectivley.

After that, I have added item1 and item2 in cart1 and item 3 in cart 2 but when we are printing the contents of cart2 we are also getting items from cart1.


Shopping cart 1 contains [Book [author=robert kiyosaki], Chips [flavour=mexican]]
Shopping cart 2 contains [Book [author=robert kiyosaki], Chips [flavour=mexican], Chips [flavour=indian]]

The reason is because the default scope of shoppingcart bean is singleton so when we are calling getBean(“shoppingcart”) method for the cart2 spring container actually is returning the same bean of cart1 .so now both cart1 and cart2 are pointing to same object or bean.

Then syntax of adding scope attribute to a bean is scope=”name of scope”.As i mentioned before the default scope is singleton so wether you add it or not spring will add this attribute internally for you like below.


<bean id="shoppingCart" class="com.codegeekslab.cart.ShoppingCart"
scope="singleton" />

Prototype Scope

To solve the problem we have another scope named as “prototype” which returns a new bean every time it’s requested.

So when you change the scope of the shoopingcart bean from singleton to prototype you will get the desired output .


<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.5.xsd">

<bean id="book" class="com.codegeekslab.items.Book">
<property name="name" value="Rich dad Poor dad" />
<property name="price" value="14" />
<property name="author" value="robert kiyosaki" />
</bean>
<bean id="chips" class="com.codegeekslab.items.Chips">
<property name="name" value="Lays" />
<property name="price" value="2" />
<property name="flavour" value="mexican" />

</bean>
<bean id="chips2" class="com.codegeekslab.items.Chips">
<property name="name" value="uncle chips" />
<property name="price" value="2" />
<property name="flavour" value="indian" />

</bean>
<bean id="shoppingCart" class="com.codegeekslab.cart.ShoppingCart"
scope="prototype" />
</beans>

output


Mar 30, 2017 11:49:31 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [beans.xml]
Mar 30, 2017 11:49:31 PM org.springframework.context.support.GenericXmlApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.GenericXmlApplicationContext@5e9f23b4: startup date [Thu Mar 30 23:49:31 IST 2017]; root of context hierarchy
Shopping cart 1 contains [Book [author=robert kiyosaki], Chips [flavour=mexican]]
Shopping cart 2 contains [Chips [flavour=indian]]

 

 

Scope Description
singleton Creates a single bean instance per Spring IoC container
prototype Creates a new bean instance each time when requested
request Creates a single bean instance per HTTP request; only valid in the context of a web application
session Creates a single bean instance per HTTP session; only valid in the context of a web application
globalSession Creates a single bean instance per global HTTP session; only valid in the context of a portal
application

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *