我有被用來創建一個全球範圍內的多個這樣的Spring配置XML文件:ClassPathXmlApplicationContext的覆蓋與同類型的豆類和不同的ID
<?xml version="1.0" encoding="UTF-8"?>
<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 class="org.springframework.context.support.ClassPathXmlApplicationContext" id="global.context">
<constructor-arg index="0">
<list>
<value>classpath:config/common/main-springconfig.xml</value>
<value>classpath:config/me/main-springconfig.xml</value>
</list>
</constructor-arg>
</bean>
</beans>
創建背景是這樣的:
private static final String springContext = "global.context";
private static final String beanRefContext = "classpath*:global-config.xml";
private ConfigurableApplicationContext springApplicationContext;
ClassPathXmlServiceLocator()
{
BeanFactoryLocator beanFactoryLocator = ContextSingletonBeanFactoryLocator.getInstance(beanRefContext);
springApplicationContext = (ConfigurableApplicationContext) beanFactoryLocator.
useBeanFactory(springContext).getFactory();
}
的問題是,每個配置有豆與同類型的defenition:some.package.BeanType,但是當背景完全實例只有一個該類型的bean是可用的。
有一個在ClassPathXmlApplicationContext的javadoc的一張紙條:
在多個配置位置的情況下,後面的bean定義將覆蓋前面加載的文件中定義的。這可以用來通過額外的XML文件故意重寫某些bean定義。
但這是否意味着即使在單獨的配置文件中定義了具有不同id的bean,也會被重寫?我怎樣才能克服這個問題?
只有當id或name匹配時才應該重寫,否則應該導致2個不同的bean。你如何檢查一個bean是否被覆蓋? – 2014-10-28 12:35:10
我通過id從上下文中檢索bean。另外還有另一個bean被some.package.BeanType bean注入。注入bean是錯誤的,儘管@Named註釋指定了正確的bean。當我使用這個注入bean所需的唯一一個子配置文件時,一切都很好。 – thereisnospoon 2014-10-28 12:41:22
'@命名'不是爲此目的,'@ Qualifier'是。 – 2014-10-28 12:43:30