【发布时间】:2009-11-18 14:14:46
【问题描述】:
我在 Spring 学习中遇到问题,需要一些帮助。
我正在学习 bean 的 prototype 范围,这基本上意味着每次有人或其他 bean 需要这个 bean 时,Spring 将创建一个新 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;
}
}
这里没有什么特别的,一些字符串、一个 Int 以及 getter 和 setter。 然后我创建了这个上下文文件:
<?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>
然后我试着玩一下,看看我对原型作用域的理解是否正确,有这个类:
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 对象的值时,它也为 product 2 更新了。在我看来,这似乎是一种奇怪的行为,不是吗?
【问题讨论】:
-
如果将 product2 的实例化移动到 product1.setPrice(80) 之后会发生什么?