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开发者_如何学C 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.
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", ...);
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.
精彩评论