在Spring配置文件中使用bean id和name之间的区别 [英] Difference between using bean id and name in Spring configuration file

查看:325
本文介绍了在Spring配置文件中使用bean id和name之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用 id 属性和名称属性在 ; ://static.springframework.org/spring/docs/2.5.x/reference/index.htmlrel =nofollow noreferrer> Spring参考, 3.2.3.1命名Bean



< blockquote>

每个bean都有一个或多个id(也称为
,称为标识符或名称;这些
术语指的是同一个东西)。这些
ids在bean托管的
容器中必须是唯一的。
bean几乎总是只有一个
id,但是如果一个bean有多个$ b



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


所以基本上 id 属性符合XML id属性标准, name 有点更灵活。一般来说,我使用 name 几乎完全。它只是似乎更多的春天。


Is there any difference between using an id attribute and name attribute on a <bean> element in a Spring configuration file?

解决方案

From the Spring reference, 3.2.3.1 Naming Beans:

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.

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

这篇关于在Spring配置文件中使用bean id和name之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆