gpt4 book ai didi

java - Spring 默认范围单例与否?

转载 作者:IT老高 更新时间:2023-10-28 13:04:43 29 4
gpt4 key购买 nike

您能否解释一下为什么 Spring 会为如下所示的 bean 配置创建两个对象,因为默认情况下 spring 默认作用域是单例?

Spring配置在这里:

<bean id="customer" class="jp.ne.goo.beans.Customer"> 
<property name="custno" value="100"></property>
<property name="custName" value="rajasekhar"> </property>
</bean>
<bean id="customer2" class="jp.ne.goo.beans.Customer">
<property name="custno" value="200"></property>
<property name="custName" value="siva"></property>
</bean>

最佳答案

Spring 的默认作用域单例。只是你对单例的理解与 Spring 对单例的定义不符。

如果您告诉 Spring 创建两个具有不同 id 和相同类的单独 bean,那么您将得到两个单独的 bean,每个具有单例范围。所有单例范围意味着当您引用具有相同 id 的东西时,您会得到相同的 bean 实例。

这里是the Spring documentation defines singleton scope :

Only one shared instance of a singleton bean is managed, and all requests for beans with an id or ids matching that bean definition result in that one specific bean instance being returned by the Spring container.

单例范围意味着使用相同的 id 检索相同的 bean,仅此而已。测试没有两个 id 引用同一个类会妨碍将映射用作 bean,并且会因为使用 BeanFactories 代理事物而变得复杂。对于 Spring 进行监管,这将涉及大量工作而收效甚微。相反,它相信用户知道他们在做什么。

如果您希望 bean 的单例性保留在多个名称中,这是可行的。您可以有多个名称引用同一个 bean,这是通过使用 alias 来完成的。 :

In a bean definition itself, you can supply more than one name for the bean, by using a combination of up to one name specified by the id attribute, and any number of other names in the name attribute. These names can be equivalent aliases to the same bean, and are useful for some situations, such as allowing each component in an application to refer to a common dependency by using a bean name that is specific to that component itself.

Specifying all aliases where the bean is actually defined is not always adequate, however. It is sometimes desirable to introduce an alias for a bean that is defined elsewhere. This is commonly the case in large systems where configuration is split amongst each subsystem, each subsystem having its own set of object definitions. In XML-based configuration metadata, you can use the element to accomplish this.

所以如果你在 bean 配置中添加一个名字:

<bean id="customer" name="customer2" 
class="jp.ne.goo.beans.Customer">
</bean>

或为在别处定义的 bean 创建一个别名:

<alias name="customer" alias="customer2"/>

那么 "customer"和 "customer2"将引用同一个 bean 实例。

关于java - Spring 默认范围单例与否?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31629993/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com