Spring配置文件中关于bean标签的id属性和name属性的说明

Every bean has one or more identifiers. 
These identifiers must be unique within the container that hosts the bean.
A bean usually has only one identifier, but if it requires more than one, the extra ones can be considered aliases.
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. 
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.

也就是说:
id和name本质上其实是相同的,都可以唯一地标识一个bean。区别是id只能定义一个值,name可以定义多个值(separated by a comma (,), semicolon (;), or white space)。

  1. 配置一个bean的时候,可以不设置id,也可以不设置name,spring默认会使用类的全限定名作为bean的标识符。
  2. 如果设置id属性,那么id就是bean的唯一标识符,在spring容器中必需唯一。
  3. 如果仅设置name属性,那么name就是bean的唯一标识符,必需在容器中唯一。
  4. 如果同时设置id和name,那么id是唯一标识符,name是别名。如果id和name的值相同,那么spring容器会自动检测并消除冲突:让这个bean只有标识符,而没有别名。
  5. name属性设置多个值且不设置id属性,那么第一个被用作标识符,其他的被视为别名。如果设置了id,那么name的所有值都是别名。
  6. 不管是标识符,还是别名,在容器中必需唯一。因为标识符和别名,都是可以用来获取bean的,如果不唯一,显然不知道获取的到底是哪儿一个bean。

 

 

 

参考文章:

https://www.iteye.com/blog/jinnianshilongnian-1413857

 

posted @   吾爱春秋  阅读(5161)  评论(0编辑  收藏  举报
编辑推荐:
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 使用C#创建一个MCP客户端
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示