spring Spring配置文件中使用bean id和name的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/874505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 03:52:11  来源:igfitidea点击:

Difference between using bean id and name in Spring configuration file

springconfiguration

提问by

Is there any difference between using an idattribute and nameattribute on a <bean>element in a Spring configuration file?

在 Spring 配置文件中的元素上使用id属性和name属性有什么区别<bean>吗?

回答by cletus

From the Spring reference, 3.2.3.1 Naming Beans:

Spring参考3.2.3.1命名豆类

Every bean has one or more ids (also called identifiers, or names; these terms refer to the same thing). These ids must be unique within the container the bean is hosted in. A bean will almost always have only one id, but if a bean has more than one id, the extra ones can essentially be considered aliases.

When using XML-based configuration metadata, you use the 'id' or 'name' attributes to specify the bean identifier(s). The 'id' attribute allows you to specify exactly one id, and as it is a real XML element ID attribute, the XML parser is able to do some extra validation when other elements reference the id; as such, it is the preferred way to specify a bean id. However, the XML specification does limit the characters which are legal in XML IDs. This is usually not a constraint, but if you have a need to use one of these special XML characters, or want to introduce other aliases to the bean, you may also or instead specify one or more bean ids, separated by a comma (,), semicolon (;), or whitespace in the 'name' attribute.

每个 bean 都有一个或多个 id(也称为标识符或名称;这些术语指的是同一件事)。这些 id 在承载 bean 的容器中必须是唯一的。 bean 几乎总是只有一个 id,但如果 bean 有多个 id,则额外的 id 基本上可以被视为别名。

使用基于 XML 的配置元数据时,您可以使用“id”或“name”属性来指定 bean 标识符。'id' 属性允许您指定一个 id,因为它是一个真正的 XML 元素 ID 属性,当其他元素引用该 id 时,XML 解析器能够做一些额外的验证;因此,它是指定 bean id 的首选方式。但是,XML 规范确实限制了 XML ID 中合法的字符。这通常不是约束,但是如果您需要使用这些特殊的 XML 字符之一,或者想为 bean 引入其他别名,您也可以指定一个或多个 bean id,用逗号 (, )、分号 (;) 或 'name' 属性中的空格。

So basically the idattribute conforms to the XML id attribute standards whereas nameis a little more flexible. Generally speaking, I use namepretty much exclusively. It just seems more "Spring-y".

所以基本上该id属性符合 XML id 属性标准,而name更灵活一些。一般来说,我name几乎只使用。它似乎更“春天”。

回答by Duncan Jones

Since Spring 3.1 the idattribute is an xsd:stringand permits the same range of characters as the nameattribute.

从 Spring 3.1 开始,该id属性是 anxsd:string并且允许与该属性具有相同范围的字符name

The only difference between an idand a nameis that a namecan contain multiple aliases separated by a comma, semicolon or whitespace, whereas an idmust be a single value.

anid和 a之间的唯一区别name是 aname可以包含由逗号、分号或空格分隔的多个别名,而 anid必须是单个值。

From the Spring 3.2 documentation:

从 Spring 3.2 文档:

In XML-based configuration metadata, you use the id and/or name attributes to specify the bean identifier(s). The id attribute allows you to specify exactly one id. Conventionally these names are alphanumeric ('myBean', 'fooService', etc), but may special characters as well. If you want to introduce other aliases to the bean, you can also specify them in the name attribute, separated by a comma (,), semicolon (;), or white space. As a historical note, in versions prior to Spring 3.1, the id attribute was typed as an xsd:ID, which constrained possible characters. As of 3.1, it is now xsd:string. Note that bean id uniqueness is still enforced by the container, though no longer by XML parsers.

在基于 XML 的配置元数据中,您使用 id 和/或 name 属性来指定 bean 标识符。id 属性允许您指定一个 id。通常,这些名称是字母数字('myBean'、'fooService' 等),但也可能是特殊字符。如果要为 bean 引入其他别名,也可以在 name 属性中指定它们,用逗号 (,)、分号 (;) 或空格分隔。作为历史记录,在 Spring 3.1 之前的版本中,id 属性被键入为 xsd:ID,这限制了可能的字符。从 3.1 开始,它现在是 xsd:string。请注意,bean id 唯一性仍由容器强制执行,但不再由 XML 解析器强制执行。

回答by pugmarx

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean idand supply the bean nameinstead.
The nameattribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

任何一个都行。这取决于您的需要:
如果您的 bean 标识符包含特殊字符,例如 ( /viewSummary.html),则不允许将其作为 bean id,因为它不是有效的 XML ID。在这种情况下,您可以跳过定义 beanid并提供 bean name
name属性还有助于alias为您的 bean定义es,因为它允许为给定的 bean 指定多个标识符。

回答by swaroop

Is there any difference between using an id attribute and name attribute on a <bean> tag

在 <bean> 标签上使用 id 属性和 name 属性有什么区别

Few minor differences exists like, using id will throw exception if not handled properly .
let me answer below question

存在一些细微的差异,例如,如果处理不当,使用 id 将引发异常。
让我回答下面的问题

Is there any difference between using an idattribute and using a nameattribute on a <bean> tag,

在 <bean> 标签上使用 id属性和使用 name属性有什么区别,

There is no difference. you will experience same effect when id or name is used on a <bean> tag .

没有区别。在 <bean> 标签上使用 id 或 name 时,您将体验到相同的效果。

How?

如何?

Both id and name attributes are giving us a means to provide identifier value to a bean (For this moment, think id means id but not identifier). In both the cases, you will see same result if you call applicationContext.getBean("bean-identifier"); .

id 和 name 属性都为我们提供了一种向 bean 提供标识符值的方法(此时,认为 id 表示 id 而不是标识符)。在这两种情况下,如果您调用 ,您将看到相同的结果applicationContext.getBean("bean-identifier");

Take @Bean, the java equivalent of <bean> tag, you wont find an id attribute. you can give your identifier value to @Bean only through name attribute.

以@Bean,<bean> 标签的java 等价物为例,你不会找到id 属性。您只能通过 name 属性将标识符值提供给 @Bean。

Let me explain it through an example :
Take this configuration file, let's call it as spring1.xml

我通过一个例子来解释一下:
以这个配置文件,我们称它为 spring1.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
  <bean id="foo" class="com.intertech.Foo"></bean>
  <bean id="bar" class="com.intertech.Bar"></bean>
</beans>

Spring returns Foo object for, Foo f = (Foo) context.getBean("foo");. Replace id="foo"with name="foo"in the above spring1.xml, You will still see the same result.

Spring 为, 返回 Foo 对象Foo f = (Foo) context.getBean("foo");。替换id="foo"name="foo"上述spring1.xml,你仍然可以看到同样的结果。

Define your xml configuration like,

定义您的 xml 配置,例如,

<?xml version="1.0" encoding="UTF-8"?>
<beans ...>
  <bean id="fooIdentifier" class="com.intertech.Foo"></bean>
  <bean name="fooIdentifier" class="com.intertech.Foo"></bean>
</beans>

You will get BeanDefinitionParsingException. It will say, Bean name 'fooIdentifier' is already used in this element. By the way, This is the same exception you will see if you have below config
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>


If you keep both id and name to the bean tag, the bean is said to have 2 identifiers. you can get the same bean with any identifier. take config as

你会得到 BeanDefinitionParsingException。它会说,Bean 名称 'fooIdentifier' 已在此元素中使用。顺便说一句,如果您有以下配置,您将看到相同的例外
<bean name="fooIdentifier" class="com.intertech.Foo"></bean>
<bean name="fooIdentifier" class="com. intertech.Foo"></bean>


如果您将 id 和 name 都保留在 bean 标记中,则认为 bean 具有 2 个标识符。您可以使用任何标识符获得相同的 bean。将配置作为

<?xml version="1.0" encoding="UTF-8"?><br>
<beans ...>
  <bean id="fooById" name="fooByName" class="com.intertech.Foo"></bean>
  <bean id="bar" class="com.intertech.Bar"></bean>
</beans>

the following code prints true

以下代码打印为真

FileSystemXmlApplicationContext context = new FileSystemXmlApplicationContext(...);
Foo fooById = (Foo) context.getBean("fooById")// returns Foo object;
Foo fooByName = (Foo) context.getBean("fooByName")// returns Foo object;
System.out.println(fooById == fooByName) //true

回答by user3202413

Is there difference in defining Id & name in ApplicationContext xml ? No As of 3.1(spring), id is also defined as an xsd:string type. It means whatever characters allowed in defining name are also allowed in Id. This was not possible prior to Spring 3.1.

在 ApplicationContext xml 中定义 Id 和 name 有区别吗?否 从 3.1(spring) 开始,id 也被定义为 xsd:string 类型。这意味着在定义名称中允许的任何字符也允许在 Id 中。这在 Spring 3.1 之前是不可能的。

Why to use name when it is same as Id ? It is 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.

为什么在与 Id 相同时使用 name ?它在某些情况下很有用,例如允许应用程序中的每个组件通过使用特定于该组件本身的 bean 名称来引用公共依赖项。

For example, the configuration metadata for subsystem A may refer to a DataSource via the name subsystemA-dataSource. The configuration metadata for subsystem B may refer to a DataSource via the name subsystemB-dataSource. When composing the main application that uses both these subsystems the main application refers to the DataSource via the name myApp-dataSource. To have all three names refer to the same object you add to the MyApp configuration metadata the following 

<bean id="myApp-dataSource" name="subsystemA-dataSource,subsystemB-dataSource" ..../>

Alternatively, You can have separate xml configuration files for each sub-system and then you can make use of
alias to define your own names.

<alias name="subsystemA-dataSource" alias="subsystemB-dataSource"/>
<alias name="subsystemA-dataSource" alias="myApp-dataSource" />

回答by chirag soni

Both idand nameare bean identifiers in Spring IOC container/ApplicationContecxt. The idattribute lets you specify exactly one id but using nameattribute you can give alias name to that bean.

双方idname在Spring IoC容器/ ApplicationContecxt豆标识符。该id属性允许您指定一个 id,但使用name属性您可以为该 bean 指定别名。

You can check the spring dochere.

您可以在此处查看 spring文档