我在Spring学习中遇到问题,需要一些帮助.
我正在学习bean的原型范围,这基本上意味着每次有人或其他bean需要这个bean时,Spring会创建一个新bean而不使用相同的bean.
所以我尝试了这段代码,假设我有这个Product类:
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;
}
}
这里没什么特别的,一些Strings,一个Int和getter and setters.
然后我创建了这个上下文文件:
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">
然后我试着玩,看看我对原型范围的理解是否正确,这个类:
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());
}
}
令我惊讶的是,答案是:
70.0
Let's change the price of this incredible game :
Price for product1 object
80.0
Price Product 2 :
80.0
因此,当我更新了product1对象的值时,它似乎也已经更新了产品2.在我看来这是一种奇怪的行为,不是吗?