spring bean & id

首先澄清一个概念: 

同名bean:多个bean 有相同的 name 或者 id,称之为同名bean 

<bean> 的id 和 name的区别 

id和name都是spring 容器中bean 的标识符。 

id: 一个bean的唯一标识  , 命名格式必须符合XML ID属性的命名规范 

name: 可以用特殊字符,并且一个bean可以用多个名称:name=“bean1,bean2,bean3” ,用逗号或者分号或者空格隔开。如果没有id,则name的第一个名称默认是id 

spring 容器如何处理同名bean? 

    同一个spring配置文件中,bean的 id、name是不能够重复的,否则spring容器启动时会报错。 

    如果一个spring容器从多个配置文件中加载配置信息,则多个配置文件中是允许有同名bean的,并且后面加载的配置文件的中的bean定义会覆盖前面加载的同名bean。 

spring 容器如何处理没有指定id、name属性的bean? 

如果 一个 <bean> 标签未指定 id、name 属性,则 spring容器会给其一个默认的id,值为其类全名。 

如果有多个<bean> 标签未指定 id、name 属性,则spring容器会按照其出现的次序,分别给其指定 id 值为 "类全名#1", "类全名#2" 

<bean class="com.xxx.UserInfo">  
    <property name="accountName" value="no-id-no-name0"></property>  
</bean>  
  
<bean class="com.xxx.UserInfo">  
    <property name="accountName" value="no-id-no-name1"></property>  
</bean>  
  
<bean class="com.xxx.UserInfo">  
    <property name="accountName" value="no-id-no-name2"></property>  
</bean>  

获取:

UserInfo u4 = (UserInfo)ctx.getBean("com.xxx.UserInfo");  
UserInfo u5 = (UserInfo)ctx.getBean("com.xxx.UserInfo#1");  
UserInfo u6 = (UserInfo)ctx.getBean("com.xxx.UserInfo#2"); 

猜你喜欢

转载自wangxinchun.iteye.com/blog/2341213