java – 导入另一个spring上下文时的Spring bean名称

在试验
Spring时遇到的这个问题,你能告诉我吗?

我这里有两个上下文.让我们将它们命名为springA.xml和springB.xml

springA.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

   <import resource="springB.xml" />

   <bean name="name2" class="java.lang.String"/>
</beans>

springB.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean name="name2,name3" class="java.lang.String"/>

</beans>

springC.xml

<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="
            http://www.springframework.org/schema/beans
            http://www.springframework.org/schema/beans/spring-beans.xsd">

   <bean name="name3,name2" class="java.lang.String"/>

</beans>

这是我的Java文件.

public static void main(String[] args) {
    BeanFactory factory = new XmlBeanFactory(new ClassPathResource("springA.xml"));

    Object obj1 = factory.getBean("name2");
    Object obj2 = factory.getBean("name3");

    System.out.println(obj1.getClass().getName() + " " + obj2.getClass().getName());
}

结果,我得到一个“java.lang.String java.lang.String”.如果我改变了位置
名称“name2,name3”到“name3,name2”(springC.xml),我得到一个“java.lang.Object java.lang.Object”.

我很困惑为什么结果是这样的.我期望该函数将返回name2的java.lang.String和name3的java.lang.Object(因为name2已经在springA.xml中使用,我假设不会使用此名称,而是使用name3 for springB.xml)

谢谢!

PS:
春天2.5
Eclipse 3.5

最佳答案 从Spring的文档:

Every bean has one or more ids (also
called identifiers, or names; these
terms refer to the same thing). These
ids must be unique within the
BeanFactory or ApplicationContext the
bean is hosted in.

根据这个,你的组合应用程序上下文是无效的,因为它包含两个具有相同ID的不同bean – 来自ContextA.xml的名为“name2”的bean和名为“name2”的bean,在ContextC.xml中别名为“name3”.我希望Spring至少发出一个警告.

回答你的问题:你不应该期望这种设置有任何明智的结果. Bean名称必须是唯一的,如果不是,则结果未定义.而“未定义”我的意思是“不太可能有所帮助”:)

希望这可以帮助.

点赞