java – Spring和scope属性
我在
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. <?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对象的值时,它似乎也已经更新了产品2.在我看来这是一种奇怪的行为,不是吗? 解决方法
您对原型范围的理解是正确的.从文档:
也就是说,我无法重现您观察到的行为(我正在运行您提供的代码).这是我用spring-2.5.6.SEC01.jar得到的: 70.0 Let's change the price of this incredible game : Price for product1 object 80.0 Price Product 2 : 70.0 我没有尝试所有版本的Spring,但你可能会使用一个有缺陷的版本(虽然非常不可能),或者某个地方存在另一个问题(更有可能). (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |