Spring配置中<bean>的id和name属性区分

来源:互联网 发布:51单片机c语言教程pda 编辑:程序博客网 时间:2024/05/22 17:02
上一篇文章中涉及到了Spring bean配置id和name的事情,以前还真没注意到,发现这是个有趣的问题。

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.

Please note that you are not required to supply a name for a bean. If no name is supplied explicitly, the container will generate a unique name for that bean. The motivations for not supplying a name for a bean will be discussed later (one use case is inner beans).——出自http://docs.spring.io/spring/docs/2.5.x/reference/beans.html#beans-beanname

《Spring专业开发指南》里面讲到这个事情。根据作者的意思,name是id的一个补充。
1)id与name 属性在作用上基本没有区别。推荐使用id。
 
2)id取值要求严格些,必须满足XML的命名规范。id是唯一的,配置文件中不允许出现两个id相同的<bean>。
 
3)name取值比较随意,甚至可以用数字开头。在配置文件中允许出现两个name相同的<bean>,在用getBean()返回实例时,后面一个Bean被返回。
 
4)如果没有id,name,则用类的全名作为name,如<bean class="test.Test">,可以使用getBean("test.Test")返回该实例。

谈谈Spring配置中的id和name属性的花拳秀腿
0 0
原创粉丝点击