Uncategorized

SCOPE OF BEANS IN SPRING USING ANNOTATIONS

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 the scope of a bean.

Types of the scope of a bean:

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

To define the scope of the bean using spring annotation you just have to add @scope(“name of the scope”) on top of your bean class.

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 and apply this @scope annotation on our bean class.

A simple spring application without any explicitly specified scope.

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 org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.codegeekslab.product.Product;
@Component
public class ShoppingCart {
private List<Product> items = new ArrayList<Product>();

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

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

ShoppingCartConfiguration.java


package com.codegeekslab.configuration;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import com.codegeekslab.cart.ShoppingCart;
import com.codegeekslab.items.Book;
import com.codegeekslab.items.Chips;
import com.codegeekslab.product.Product;

@Configuration
public class ShoppingCartConfiguration {

@Bean
public Product book() {
Book book = new Book();
book.setName("Rich dad Poor dad");
book.setAuthor("robert kiyosaki");
book.setPrice(14);
return book;
}

@Bean
public Chips chips() {
Chips chips = new Chips();
chips.setName("Lays");
chips.setFlavour("mexican");
chips.setPrice(2);
return chips;
}

@Bean
public Chips chips2() {
Chips chips = new Chips();
chips.setName("uncle chips");
chips.setFlavour("indian");
chips.setPrice(2);
return chips;
}

/*@Bean
@Scope("prototype")
public ShoppingCart shoppingCart() {
ShoppingCart shoppingCart = new ShoppingCart();
return shoppingCart;
}*/

}

Test.java


package com.codegeekslab.test;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

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");

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
context.scan("com.codegeekslab.configuration","com.codegeekslab.cart");
// context.register(CellPhoneConfiguration.class);
context.refresh();
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);
ShoppingCart cart2 = (ShoppingCart) context.getBean("shoppingCart");
cart2.addItem(item3);

System.out.println("Shopping cart 1 contains " + cart1.getItems());
System.out.println("Shopping cart 2 contains " + cart2.getItems());
}
}

Output

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 ShoppingCartConfiguration.java 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
public Product book() {
Book book = new Book();
book.setName("Rich dad Poor dad");
book.setAuthor("robert kiyosaki");
book.setPrice(14);
return book;
}

@Bean
public Chips chips() {
Chips chips = new Chips();
chips.setName("Lays");
chips.setFlavour("mexican");
chips.setPrice(2);
return chips;
}

@Bean
public Chips chips2() {
Chips chips = new Chips();
chips.setName("uncle chips");
chips.setFlavour("indian");
chips.setPrice(2);
return chips;
}

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

</div>
<div class="EnlighterJSWrapper eclipseEnlighterJSWrapper">@Component
public class ShoppingCart {
private List<Product> items = new ArrayList<Product>();public void addItem(Product item) {
items.add(item);
}public List<Product> getItems() {
return items;
}
}
Now in our Test.java I have created beans of all the three products and named them as item1,item2 and item3.
Product item1 = (Product) context.getBean("book");
Product item2 = (Product) context.getBean("chips");
Product item3 = (Product) context.getBean("chips2");

And then i have created the 2 carts by creating beans of ShoppingCart class named as “cart1” and “cart2” respectivley and added above items which we created.
ShoppingCart cart1 = (ShoppingCart) context.getBean("shoppingCart");
cart1.addItem(item1);
cart1.addItem(item2);
ShoppingCart cart2 = (ShoppingCart) context.getBean("shoppingCart");
cart2.addItem(item3);

Now the important thing to note here is when we try to get the items which we added into cart2 we are also getting items which we have added into cart1 which we were not expecting.
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 as said before the default scope of every bean is singleton because of this spring assign the default scope singleton to shoppingcart bean. 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.

Spring adds this singleton scope implicitly to every bean.In our case spring has added @Scope(“singleton”) on top of our ShoppingCart class like this


@Component
@Scope("singleton")
public class ShoppingCart { }

To solve the above problem spring provides Prototype scope.

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 ShoppingCart bean from singleton to prototype you will get the desired output.


package com.codegeekslab.cart;

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

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.codegeekslab.product.Product;
@Component
@Scope("prototype")
public class ShoppingCart {
private List<Product> items = new ArrayList<Product>();

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

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

output


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

Leave a Reply

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