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。

猜你喜欢

转载自www.cnblogs.com/AbnerRao/p/12953121.html