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

上一篇文章中涉及到了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")返回该实例。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值