(4)Bean的命名

来源:互联网 发布:淘宝微型打印机打印纸 编辑:程序博客网 时间:2024/06/15 22:19

一个简单的IoC的例子

1、只有类名
<bean class="shuai.spring.study.HelloImpl"></bean>

HelloApi helloApi = context.getBean(HelloApi.class) ;

2、指定id,必须在ioc容器唯一

<bean id="hello" class="shuai.spring.study.HelloImpl"></bean>

HelloApi helloApi = context.getBean("hello",HelloApi.class) ;

3、指定name,必须在ioc中唯一

<bean name="hello" class="shuai.spring.study.HelloImpl"></bean>

HelloApi helloApi = context.getBean("hello",HelloApi.class) ;

跟2一样,就是id换成name了。

<bean id="hello" class="shuai.spring.study.HelloImpl"></bean>    <bean name="hello" class="shuai.spring.study.HelloImpl"></bean>

这样是报错了,我的理解是:id和name可以理解为混用的标识(至少在java层面),一种标识只能配一个bean。当然,写两个id="hello"或者name="hello"也是错的。

4、指定id和name

<bean id="hello" name="hello1" class="shuai.spring.study.HelloImpl"></bean>
HelloApi helloApi = context.getBean("hello",HelloApi.class) ;HelloApi helloApi1 = context.getBean("hello1",HelloApi.class) ;

这个id和name可以相同,比如都是hello,我的理解,一个bean,随便配置id,name,只要不跟别的bean重复就行了。

5、指定多个name

<bean id="hello" name="hello1 hello2,hello3;hello4;hello;hello4" class="shuai.spring.study.HelloImpl"></bean>

多个name直接可以用空格、逗号、分号隔开,而且名字可以和id或者其它name相同(同一个bean里的),当然,不能跟其它的bean重复,其它bean的id或name不能是hello,hello1,hello2,hello3,hello4了。

String[] helloAlias = context.getAliases("hello2");  //获取hello2的别名,不包括hello2System.out.println(helloAlias.length);for (String string : helloAlias) {System.out.println(string);}
输出结果:

4
hello
hello1
hello4
hello3

不能指定多个id

<bean id="hello;hello1"  class="shuai.spring.study.HelloImpl"></bean>
这样是报错的。

6、使用<alias>添加别名

<bean id="hello" name="hello1 hello2,hello3;hello4;hello4" class="shuai.spring.study.HelloImpl"></bean>    <alias alias="hello5" name="hello"/><alias alias="hello6" name="hello2"/><alias alias="hello7" name="hello6"/>

alias标签里的alias是设置的别名,不能写多个,比如hello5;hello6,它会以为hello;hello是别名,name里是关了的标识,随便一个就行,不管是id还是name,还是alias
使用上面代码将输出:

7
hello
hello1
hello4
hello5
hello6
hello7
hello3

但是alias里面的alias是可以跟其它bean的id或name重复的,还不报错,比如增加一个

<bean name="hello6" class="shuai.spring.study.HelloImpl"></bean>

这样是不会报错的【疑问】

7、为什么会同时存在id和name

从定义来看,name或id如果指定它们中的一个时都作为“标识符”,那为什么还要有id和name同时存在呢?这是因为当使用基于XML的配置元数据时,在XML中id是一个真正的XML id属性,因此当其他的定义来引用这个id时就体现出id的好处了,可以利用XML解析器来验证引用的这个id是否存在,从而更早的发现是否引用了一个不存在的bean,而使用name,则可能要在真正使用bean时才能发现引用一个不存在的bean。【摘抄】

8、一些问题

比如配置文件这么写

<bean id="hello" class="shuai.spring.study.HelloImpl"></bean>  <bean name="hello1" class="shuai.spring.study.HelloImpl"></bean>
获取bean只根据class

HelloApi helloApi = context.getBean(HelloApi.class);

这样是会报错的,大概意思是两个bean,不知道是哪个

但是如果在配置文件里添加一句

<alias name="hello" alias="hello1"/>


这样就不会报错了


有时间深入了解下alias



原创粉丝点击