Spring configuration file creates beans and interconnects them. Is this correct? I have a chain of beans in my application but want to test it with smaller chains. Can I have multiple chains defined with Spring? Or only one bean structure is allowed?
EXAMPLE
Suppose this is production config:
<bean id="provider"
class="tests.Provider">
</bean>
<bean id="processor1" class="tests.Processor1">
<property name="input" ref="provider"/>
</bean>
<bean id="processor2" class="tests.Processor2">
<property name="input" ref="processor1"/>
</bean>
<bean id="consumer" class="tests.Consumer">
<property name="input" ref="processor2"/>
</bean>
And I want to test in the following configs:
<bean id="provider"
class="tests.Provider">
</bean>
<bean id="analyzer" class="tests.Analyzer">
<property name="input" ref="provider"/>
</bean>
And:
<bean id="provider"
class="tests.Provider">
</bean>
<bean id="processor1" class="tests.Processor1">
<property name="input" ref="provider"/>
</bean>
<bean id="analyzer" class="tests.Analyzer">
<property name="input" ref="processor1"/>
</bean>
And so on, attaching beans one by one.
Yes, you can.
You can break overall configuration of Spring application context for your application into parts (XML files if you use XML configuration, packages with
@Componentsif you use classpath scanning,@Configurations if you use Java-based configuration) and construct an application context using a subset of these parts.So, if your application has two features
fooandbar, you can declare beans used by these features infoo.xmlandbar.xmlrespectively (if you use XML configuration), and import them from the main configuration of your application (such asapplicationContext.xml).Now, if you want to write integration test for
baryou can create application context frombar.xmlonly (@ContextConfiguration("bar.xml")). Obviously, you should take care of interdependencies between different parts of your configuration. For example, if bothfoo.xmlandbar.xmldepend on beans declared indb.xml, you may want to create something liketest-db.xmland configure your integration test forbaras@ContextConfiguration({"bar.xml", "test-db.xml"}).Note that this approach requres some discipline, especially if you use classpath scanning – in this case parts of your configuration are defined by packages, therefore you need to follow “package by feature, not by layer” rule.
See also: