本文介绍如何给Spring的Bean配置文件的Bean定义别名?
原始的
<bean id="business" class="onlyfun.caterpillar.device.Business">
<property name="writer">
<ref bean="writer"/>
</property>
</bean>
id="business"学名叫做“识别名称”
怎么给 business设置别名呢?
有两种方法:
1、使用独立的alias语法 。如
<bean id="writer" class="onlyfun.caterpillar.device.FloppyWriter"></bean>
<alias name="writer" alias="writerAlias" />
<alias name="writer" alias="writerAlias2" />
则 writerAlias 就是 writer的别名,
writerAlias2 也是 writer的别名
2、使用<bean>标签的“name”属性来设置别名。
如:
<bean id="business" name="businessAlias1,businessAlias2,businessAlias3" class="onlyfun.caterpillar.device.Business" />
需要注意的地方:
<bean id="writer" class="onlyfun.caterpillar.device.FloppyWriter"></bean>
<alias name="writer" alias="writer1" />
<alias name="writer" alias="writer2" />
<alias name="writer" alias="writer3" />
<alias name="writer3" alias="writer4" />
<alias name="writer4" alias="writer5" />
<alias name="writer5" alias="writer6" />
<alias name="writer6" alias="writer7" />
(1)第一种情况
String [] aliasStrArr = context.getAliases("writer7");
String s = "";
for (int i = 0; i < aliasStrArr.length; i++) {
s += aliasStrArr[i] + " - ";
}
System.out.println(s);
不运行 你觉得打印会是啥?
正确答案是
writer - writer2 - writer1 - writer3 -
(2)第二种情况
String [] aliasStrArr = context.getAliases("writer2");
String s = "";
for (int i = 0; i < aliasStrArr.length; i++) {
s += aliasStrArr[i] + " - ";
}
System.out.println(s);
不运行 你觉得打印会是啥?
writer - writer1 - writer3 -
(2)第三种情况
String [] aliasStrArr = context.getAliases("writer");
String s = "";
for (int i = 0; i < aliasStrArr.length; i++) {
s += aliasStrArr[i] + " - ";
}
System.out.println(s);
不运行 你觉得打印会是啥?
writer2 - writer1 - writer3 -
总结:
为什么会这样呢?
答案:spring这个方法规定就是这样滴:
/**
* Return the aliases for the given bean name, if any.
* All of those aliases point to the same bean when used in a {@link #getBean} call.
* <p>If the given name is an alias, the corresponding original bean name
* and other aliases (if any) will be returned, with the original bean name
* being the first element in the array.
* <p>Will ask the parent factory if the bean cannot be found in this factory instance.
* @param name the bean name to check for aliases
* @return the aliases, or an empty array if none
* @see #getBean
*/
看到没,不再翻译了。
所有别名都引用的是同一个实例。