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)。
- 配置一個bean的時候,可以不設置id,也可以不設置name,spring默認會使用類的全限定名作為bean的標識符。
- 如果設置id屬性,那么id就是bean的唯一標識符,在spring容器中必需唯一。
- 如果僅設置name屬性,那么name就是bean的唯一標識符,必需在容器中唯一。
- 如果同時設置id和name,那么id是唯一標識符,name是別名。如果id和name的值相同,那么spring容器會自動檢測並消除沖突:讓這個bean只有標識符,而沒有別名。
- name屬性設置多個值且不設置id屬性,那么第一個被用作標識符,其他的被視為別名。如果設置了id,那么name的所有值都是別名。
- 不管是標識符,還是別名,在容器中必需唯一。因為標識符和別名,都是可以用來獲取bean的,如果不唯一,顯然不知道獲取的到底是哪兒一個bean。
參考文章:
https://www.iteye.com/blog/jinnianshilongnian-1413857