views:

46

answers:

2

In the setup of my test cases, I have this code:

    ApplicationContext context = new ClassPathXmlApplicationContext(
            "spring/common.xml"
    );
    StaticListableBeanFactory testBeanFactory = new StaticListableBeanFactory();

How do I connect the two in such a way that tests can register beans in the testBeanFactory during setup and the rest of the application uses them instead of the ones defined in common.xml?

Note: I need to mix a static (common.xml) and a dynamic configuration. I can't use XML for the latter because that would mean to write > 1000 XML files.

A: 

An alternative you might like to try is to have a Test.xml with the bean definitions that imports your common.xml:

<import resource="spring/common.xml"/>

<bean id="AnIdThatOverridesSomethingInCommon"/>

You can only have one bean definition with a particular id - in the same file it's an XML validation error, in different files Spring will override the definition.

Edit: Just noticed that this is not suitable for your case - I'll leave it here for completeness.

cyborg
No downvote because of the edit :-)
Aaron Digulla
Thanks - this is actually what I use but I guess you wouldn't want to if you're trying to apply this to a load of existing tests.
cyborg
+2  A: 

You can use ConfigurableListableBeanFactory.registerSingleton() instead of StaticListableBeanFactory.addBean():

ApplicationContext context = new ClassPathXmlApplicationContext(
            "spring/common.xml" 
    ); 

GenericApplicationContext child = new GenericApplicationContext(context);

child.getBeanFactory().registerSingleton("foo", ...);
axtavt