gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-11-01 03:29:42 25 4
gpt4 key购买 nike

能否请教一下我在试用Spring时遇到的这个问题。

我这里有 2 个上下文。我们将它们命名为 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对于 springB.xml)

谢谢!

附言: Spring 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 - 您的 bean 来自 ContextA.xml,名为“name2”,您的 bean 名为“name2”,在 ContextC 中别名为“name3”。 xml。我希望 Spring 至少对此发出警告。

回答您的问题:您不应期望从这种设置中获得任何理智的结果。 Bean 名称必须是唯一的,如果不是,则结果是未定义的。我所说的“未定义”是指“不太可能有帮助”:)

希望这对您有所帮助。

关于java - 导入另一个 spring 上下文时的 spring bean 名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3854001/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com