Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/377.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何强制spring容器不返回bean的单例实例?_Java_Spring - Fatal编程技术网

Java 如何强制spring容器不返回bean的单例实例?

Java 如何强制spring容器不返回bean的单例实例?,java,spring,Java,Spring,当我在BeanFactory上调用getBean(name)时,我会返回在应用程序上下文中定义的bean实例。但是,当我再次调用getBean(name)时(使用相同的名称),我会得到相同的bean实例。我知道这在某些(许多?)情况下是多么理想,但是我如何告诉BeanFactory给我一个新实例呢 示例Spring配置(简洁地说……我省略了一些详细内容,但这应该能让人明白这一点): 请注意,两者都有相同的OOID…所以这些是相同的实例…但我需要不同的实例。默认值为singleton,但您可以将其

当我在
BeanFactory
上调用
getBean(name)
时,我会返回在应用程序上下文中定义的bean实例。但是,当我再次调用
getBean(name)
时(使用相同的名称),我会得到相同的bean实例。我知道这在某些(许多?)情况下是多么理想,但是我如何告诉
BeanFactory
给我一个新实例呢

示例Spring配置(简洁地说……我省略了一些详细内容,但这应该能让人明白这一点):


请注意,两者都有相同的OOID…所以这些是相同的实例…但我需要不同的实例。

默认值为singleton,但您可以将其设置为prototype、request、session或global session。

您需要告诉spring您需要的是prototype bean而不是singleton bean

<bean id="beanA" class="misc.BeanClass" scope="prototype"/>


这将为每个请求提供一个新实例。

这样做了。有两件事使我脱轨:1。最初,我在寻找getBean(String)的参数,而不是配置中的属性。。。2.在Spring1.x(我以前的Spring体验)中,该属性被称为“singleton”,但在2.5中显然不起作用。是的,他们在Spring2.x中将其更改为“scope”,以适应请求、会话和全局会话。如果您通过Java类(
@Configuration
)进行配置,则可以
使用@scope(“prototype”)
在bean定义方法中
for(int i = 0;i++;i<=1) {
    ApplicationContext context = ClassPathXmlApplicationContext("context.xml");
    Object o = context.getBean("beanA");

    System.out.println(o.toString());  // Note: misc.BeanA does not implement 
                                       // toString(), so this will display the OOID
                                       // so that we can tell if it's the same
                                       // instance
}
misc.BeanClass@139894
misc.BeanClass@139894
<bean id="beanA" class="misc.BeanClass" scope="prototype"/>