Java Spring和scope属性
我在春季学习中遇到了一个问题,需要一些帮助 我了解了bean的原型范围,这基本上意味着每次有人或其他bean需要这个bean时,Spring都会创建一个新bean,而不是使用相同的bean 所以我尝试了这段代码,假设我有这个Java Spring和scope属性,java,spring,Java,Spring,我在春季学习中遇到了一个问题,需要一些帮助 我了解了bean的原型范围,这基本上意味着每次有人或其他bean需要这个bean时,Spring都会创建一个新bean,而不是使用相同的bean 所以我尝试了这段代码,假设我有这个产品类: public class Product { private String categoryOfProduct; private String name; private String brand; private doubl
产品
类:
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。
然后我创建了这个上下文文件:
然后我试着玩,看看我对原型范围的理解是否正确,这门课:
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对象的值时,Product2的值也被更新了。在我看来,这似乎是一种奇怪的行为,不是吗?bean部署的原型模式导致每次对特定bean的请求完成时都创建一个新的bean实例 因此,您是正确的,每个调用都应该提供一个新实例。无法复制:
70.0
Let's change the price of this incredible game :
Price for product1 object
80.0
Price Product 2 :
70.0
您正在使用您和它查看同一个XML文件吗?您对原型范围的理解是正确的。从文件中: bean部署的非单例原型范围导致每次对该特定bean发出请求时(即,它被注入到另一个bean中,或者通过容器上的编程
getBean()
方法调用被请求)都创建一个新的bean实例
也就是说,我无法重现您观察到的行为(我正在运行您提供的代码)。这就是我通过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
70
让我们来改变这个不可思议的游戏的价格:
product1对象的价格
80
价格产品2:
70
我没有尝试所有版本的Spring,但您可能使用了有缺陷的版本(虽然可能性很小),或者某个地方出现了另一个问题(可能性更大)。我只有这个上下文文件。但我认为这是IntelliJ的问题。很高兴我正确理解了原型的概念,这使得我在上下文文件中的更改完全被忽略。我看到当我有一个bean在里面时,Spring在尝试实例化它时说没有这个名称的bean。。。奇怪
谢谢大家 如果将product2的实例化移动到product1.setPrice(80)之后会发生什么?谢谢,我也在使用Spring2.5.6。我认为这是IntelliJ中的源文件夹的问题。我意识到包含此上下文文件的文件夹在我的IntelliJ配置中不再被引用为源文件夹,因此我所做的任何更改都没有考虑在内,因此此原型范围实际上没有写入xml。。。