我在Spring學習中面臨一個問題,需要一些幫助。Spring和範圍屬性
我正在學習有關原型範圍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
如此看來,當我已經更新了產品1對象的值,它已被更新,以及對產品2.在我看來是一個奇怪的行爲不是嗎?
如果將product2的實例化移至product1.setPrice(80)之後會發生什麼? – 2009-11-18 14:28:39