Search code examples
springapplicationcontext

ClassPathXmlApplicationContext created from several config files overrides beans with the same types and different ids


I have multiple spring config xml files which are being used to create one global context like this:

<?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>

I create context like this:

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();
}

The problem is that each config has defenition of bean with the same type: some.package.BeanType, but when context is fully instantiated there is only one bean of that type is available.

There is a note in ClassPathXmlApplicationContext javadoc:

In case of multiple config locations, later bean definitions will override ones defined in earlier loaded files. This can be leveraged to deliberately override certain bean definitions via an extra XML file.

But does it mean that even beans with different ids defined in separate config files will be overriden? How can I overcome this issue?


Solution

  • Finally, I found the root cause of the problem. Spring have been working correctly all the time. The problem was in third party class (so called: some.package.BeanType).