Hi everyone,
I am facing a problem in my Spring learning and would need some help, I don't think this require strong Spring skills as this is a beginner question.
I was learning about the prototype scope of a bean, which basically mean that each time this bean will be required by someone or some other beans, Spring will create a new bean and not use the same one.
So I tried this bit of code, let's say I have this product class :
public class Product {
private String categoryOfProduct;
private String name;
private String brand;
private double price;
public String getCategoryOfProduct() {
return categoryOfProduct;
}
public void setCategoryOfProduct(String categoryOfProduct) {
this.categoryOfProduct = categoryOfProduct;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
} }
Nothing special here, some Strings, an Int and the getters and setters. Then I created this context 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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="product" class="com.springDiscovery.org.product.Product" scope="prototype">
<property name="brand" value="Sega"/>
<property name="categoryOfProduct" value="Video Games"/>
<property name="name" value="Sonic the Hedgehog"/>
<property name="price" value="70"/>
</bean>
</beans>
Then I tried to play and see if my understanding of the prototype scope was right, with this class :
package com.springDiscovery.org.menu;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.springDiscovery.org.product.Product;
public class menu {
public static void main(String[] args)
{
ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");
Product product1 = (Product) context.getBean("product");
Product product2 = (Product) context.getBean("product");
System.out.println(product1.getPrice());
System.out.println("Let's change the price of this incredible game : ");
product1.setPrice(80);
System.out.println("Price for product1 object");
System.out.println(product1.getPrice());
System.out.println("Price Product 2 : ");
System.out.println(product2.getPrice());
}
}
Surprisingly for me the answer is :
70.0
Let's change the price of this incredible game :
Price for product1 object
80.0
Price Product 2 :
80.0
So it seems that when I have updated the value of the product1 object, it has been updated as well for product 2. It seems to me to be a strange behaviour, isn't it ?
Thanks for your answers.